

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta name="referrer" content="no-referrer" />
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" href="/img/fyy.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="fyy-coding">
  <meta name="keywords" content="">
  
    <meta name="description" content="实战篇Redis开篇导读 短信登录  使用redis共享session来实现  商户查询缓存  理解缓存击穿，缓存穿透，缓存雪崩等问题  优惠卷秒杀  Redis的计数器功能， 结合Lua完成高性能的redis操作，同时学会Redis分布式锁的原理，包括Redis的三种消息队列  附近的商户  我们利用Redis的GEOHash来完成对于地理坐标的操作  UV统计  主要是使用Redis来完成统计">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis实战">
<meta property="og:url" content="http://example.com/2023/05/17/Redis/Redis%E5%AE%9E%E6%88%98/index.html">
<meta property="og:site_name" content="fyy-coding">
<meta property="og:description" content="实战篇Redis开篇导读 短信登录  使用redis共享session来实现  商户查询缓存  理解缓存击穿，缓存穿透，缓存雪崩等问题  优惠卷秒杀  Redis的计数器功能， 结合Lua完成高性能的redis操作，同时学会Redis分布式锁的原理，包括Redis的三种消息队列  附近的商户  我们利用Redis的GEOHash来完成对于地理坐标的操作  UV统计  主要是使用Redis来完成统计">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302007.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302008.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302010.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302011.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302012.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302013.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302014.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302015.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302017.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302018.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302019.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302020.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302021.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302022.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302023.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302024.gif">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302025.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302026.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302027.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302028.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302029.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302030.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302031.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302032.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302033.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302035.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302036.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302037.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302038.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302039.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302040.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302041.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302042.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302043.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302044.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302045.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302046.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302047.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302048.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302049.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302050.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302051.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302052.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302053.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302054.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302055.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302056.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302057.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302058.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302059.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302060.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302061.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302062.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302063.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302064.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302066.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302069.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302070.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302071.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302072.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302073.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302074.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302075.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302076.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302077.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302078.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302079.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302080.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302081.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302082.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302083.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302084.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302085.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302086.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302087.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302088.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302089.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302090.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302091.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302092.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302093.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302095.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302098.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302099.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302100.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302101.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302102.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302103.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302104.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302105.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302106.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302107.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302108.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302109.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302110.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302111.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302112.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302114.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302116.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302117.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302118.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302119.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302120.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302121.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302122.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302123.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302124.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302125.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302126.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302127.png">
<meta property="og:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302128.png">
<meta property="article:published_time" content="2023-05-17T09:13:03.000Z">
<meta property="article:modified_time" content="2024-03-26T12:55:48.111Z">
<meta property="article:author" content="fyy">
<meta property="article:tag" content="Redis">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302007.png">
  
  
  
  <title>Redis实战 - fyy-coding</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","app_key":"96APiPOtZEiCQlv5h3jjZfbC","server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>fyy-coding</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Redis实战"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-17 17:13" pubdate>
          2023年5月17日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          32k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          270 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Redis实战</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="实战篇Redis"><a href="#实战篇Redis" class="headerlink" title="实战篇Redis"></a>实战篇Redis</h1><h2 id="开篇导读"><a href="#开篇导读" class="headerlink" title="开篇导读"></a>开篇导读</h2><ul>
<li>短信登录</li>
</ul>
<p>使用redis共享session来实现</p>
<ul>
<li>商户查询缓存</li>
</ul>
<p>理解缓存击穿，缓存穿透，缓存雪崩等问题</p>
<ul>
<li>优惠卷秒杀</li>
</ul>
<p>Redis的计数器功能， 结合Lua完成高性能的redis操作，同时学会Redis分布式锁的原理，包括Redis的三种消息队列</p>
<ul>
<li>附近的商户</li>
</ul>
<p>我们利用Redis的GEOHash来完成对于地理坐标的操作</p>
<ul>
<li>UV统计</li>
</ul>
<p>主要是使用Redis来完成统计功能</p>
<ul>
<li>用户签到</li>
</ul>
<p>使用Redis的BitMap数据统计功能</p>
<ul>
<li>好友关注</li>
</ul>
<p>基于Set集合的关注、取消关注，共同关注等等功能，这一块知识咱们之前就讲过，这次我们在项目中来使用一下</p>
<ul>
<li>打人探店</li>
</ul>
<p>基于List来完成点赞列表的操作，同时基于SortedSet来完成点赞的排行榜功能</p>
<p>以上这些内容咱们统统都会给小伙伴们讲解清楚，让大家充分理解如何使用Redis</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302007.png" srcset="/img/loading.gif" lazyload alt="1653056228879"></p>
<h2 id="1、短信登录"><a href="#1、短信登录" class="headerlink" title="1、短信登录"></a>1、短信登录</h2><h3 id="1-1、导入黑马点评项目"><a href="#1-1、导入黑马点评项目" class="headerlink" title="1.1、导入黑马点评项目"></a>1.1、导入黑马点评项目</h3><h4 id="1-1-1-、导入SQL"><a href="#1-1-1-、导入SQL" class="headerlink" title="1.1.1 、导入SQL"></a>1.1.1 、导入SQL</h4><p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302008.png" srcset="/img/loading.gif" lazyload alt="1653057872536"></p>
<h4 id="1-1-2、有关当前模型"><a href="#1-1-2、有关当前模型" class="headerlink" title="1.1.2、有关当前模型"></a>1.1.2、有关当前模型</h4><p>手机或者app端发起请求，请求我们的nginx服务器，nginx基于七层模型走的事HTTP协议，可以实现基于Lua直接绕开tomcat访问redis，也可以作为静态资源服务器，轻松扛下上万并发， 负载均衡到下游tomcat服务器，打散流量，我们都知道一台4核8G的tomcat，在优化和处理简单业务的加持下，大不了就处理1000左右的并发， 经过nginx的负载均衡分流后，利用集群支撑起整个项目，同时nginx在部署了前端项目后，更是可以做到动静分离，进一步降低tomcat服务的压力，这些功能都得靠nginx起作用，所以nginx是整个项目中重要的一环。</p>
<p>在tomcat支撑起并发流量后，我们如果让tomcat直接去访问Mysql，根据经验Mysql企业级服务器只要上点并发，一般是16或32 核心cpu，32 或64G内存，像企业级mysql加上固态硬盘能够支撑的并发，大概就是4000起~7000左右，上万并发， 瞬间就会让Mysql服务器的cpu，硬盘全部打满，容易崩溃，所以我们在高并发场景下，会选择使用mysql集群，同时为了进一步降低Mysql的压力，同时增加访问的性能，我们也会加入Redis，同时使用Redis集群使得Redis对外提供更好的服务。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302010.png" srcset="/img/loading.gif" lazyload alt="1653059409865"></p>
<h4 id="1-1-3、导入后端项目"><a href="#1-1-3、导入后端项目" class="headerlink" title="1.1.3、导入后端项目"></a>1.1.3、导入后端项目</h4><p>在资料中提供了一个项目源码：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302011.png" srcset="/img/loading.gif" lazyload alt="1653060237073"></p>
<h4 id="1-1-4、导入前端工程"><a href="#1-1-4、导入前端工程" class="headerlink" title="1.1.4、导入前端工程"></a>1.1.4、导入前端工程</h4><p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302012.png" srcset="/img/loading.gif" lazyload alt="1653060337562"></p>
<h4 id="1-1-5-运行前端项目"><a href="#1-1-5-运行前端项目" class="headerlink" title="1.1.5 运行前端项目"></a>1.1.5 运行前端项目</h4><p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302013.png" srcset="/img/loading.gif" lazyload alt="1653060588190"></p>
<h3 id="1-2-、基于Session实现登录流程"><a href="#1-2-、基于Session实现登录流程" class="headerlink" title="1.2 、基于Session实现登录流程"></a>1.2 、基于Session实现登录流程</h3><p><strong>发送验证码：</strong></p>
<p>用户在提交手机号后，会校验手机号是否合法，如果不合法，则要求用户重新输入手机号</p>
<p>如果手机号合法，后台此时生成对应的验证码，同时将验证码进行保存，然后再通过短信的方式将验证码发送给用户。</p>
<p><strong>短信验证码登录、注册：</strong></p>
<p>用户将验证码和手机号进行输入，后台从session中拿到当前验证码，然后和用户输入的验证码进行校验，如果不一致，则无法通过校验，如果一致，则后台根据手机号查询用户，如果用户不存在，则为用户创建账号信息，保存到数据库，无论是否存在，都会将用户信息保存到session中，方便后续获得当前登录信息</p>
<p><strong>校验登录状态:</strong></p>
<p>用户在请求时候，会从cookie中携带者JsessionId到后台，后台通过JsessionId从session中拿到用户信息，如果没有session信息，则进行拦截，如果有session信息，则将用户信息保存到threadLocal中，并且放行</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302014.png" srcset="/img/loading.gif" lazyload alt="1653066208144"></p>
<h3 id="1-3-、实现发送短信验证码功能"><a href="#1-3-、实现发送短信验证码功能" class="headerlink" title="1.3 、实现发送短信验证码功能"></a>1.3 、实现发送短信验证码功能</h3><p><strong>页面流程</strong></p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302015.png" srcset="/img/loading.gif" lazyload alt="1653067054461"></p>
<p><strong>具体代码如下</strong></p>
<p><strong>贴心小提示：</strong></p>
<p>具体逻辑上文已经分析，我们仅仅只需要按照提示的逻辑写出代码即可。</p>
<ul>
<li>发送验证码</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">sendCode</span><span class="hljs-params">(String phone, HttpSession session)</span> &#123;<br>    <span class="hljs-comment">// 1.校验手机号</span><br>    <span class="hljs-keyword">if</span> (RegexUtils.isPhoneInvalid(phone)) &#123;<br>        <span class="hljs-comment">// 2.如果不符合，返回错误信息</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;手机号格式错误！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.符合，生成验证码</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">code</span> <span class="hljs-operator">=</span> RandomUtil.randomNumbers(<span class="hljs-number">6</span>);<br><br>    <span class="hljs-comment">// 4.保存验证码到 session</span><br>    session.setAttribute(<span class="hljs-string">&quot;code&quot;</span>,code);<br>    <span class="hljs-comment">// 5.发送验证码</span><br>    log.debug(<span class="hljs-string">&quot;发送短信验证码成功，验证码：&#123;&#125;&quot;</span>, code);<br>    <span class="hljs-comment">// 返回ok</span><br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>登录</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">login</span><span class="hljs-params">(LoginFormDTO loginForm, HttpSession session)</span> &#123;<br>    <span class="hljs-comment">// 1.校验手机号</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">phone</span> <span class="hljs-operator">=</span> loginForm.getPhone();<br>    <span class="hljs-keyword">if</span> (RegexUtils.isPhoneInvalid(phone)) &#123;<br>        <span class="hljs-comment">// 2.如果不符合，返回错误信息</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;手机号格式错误！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.校验验证码</span><br>    <span class="hljs-type">Object</span> <span class="hljs-variable">cacheCode</span> <span class="hljs-operator">=</span> session.getAttribute(<span class="hljs-string">&quot;code&quot;</span>);<br>    <span class="hljs-type">String</span> <span class="hljs-variable">code</span> <span class="hljs-operator">=</span> loginForm.getCode();<br>    <span class="hljs-keyword">if</span>(cacheCode == <span class="hljs-literal">null</span> || !cacheCode.toString().equals(code))&#123;<br>         <span class="hljs-comment">//3.不一致，报错</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;验证码错误&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">//一致，根据手机号查询用户</span><br>    <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;phone&quot;</span>, phone).one();<br><br>    <span class="hljs-comment">//5.判断用户是否存在</span><br>    <span class="hljs-keyword">if</span>(user == <span class="hljs-literal">null</span>)&#123;<br>        <span class="hljs-comment">//不存在，则创建</span><br>        user =  createUserWithPhone(phone);<br>    &#125;<br>    <span class="hljs-comment">//7.保存用户信息到session中</span><br>    session.setAttribute(<span class="hljs-string">&quot;user&quot;</span>,user);<br><br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-4、实现登录拦截功能"><a href="#1-4、实现登录拦截功能" class="headerlink" title="1.4、实现登录拦截功能"></a>1.4、实现登录拦截功能</h3><p><strong>温馨小贴士：tomcat的运行原理</strong></p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302017.png" srcset="/img/loading.gif" lazyload alt="1653068196656"></p>
<p>当用户发起请求时，会访问我们像tomcat注册的端口，任何程序想要运行，都需要有一个线程对当前端口号进行监听，tomcat也不例外，当监听线程知道用户想要和tomcat连接连接时，那会由监听线程创建socket连接，socket都是成对出现的，用户通过socket像互相传递数据，当tomcat端的socket接受到数据后，此时监听线程会从tomcat的线程池中取出一个线程执行用户请求，在我们的服务部署到tomcat后，线程会找到用户想要访问的工程，然后用这个线程转发到工程中的controller，service，dao中，并且访问对应的DB，在用户执行完请求后，再统一返回，再找到tomcat端的socket，再将数据写回到用户端的socket，完成请求和响应</p>
<p>通过以上讲解，我们可以得知 每个用户其实对应都是去找tomcat线程池中的一个线程来完成工作的， 使用完成后再进行回收，既然每个请求都是独立的，所以在每个用户去访问我们的工程时，我们可以使用threadlocal来做到线程隔离，每个线程操作自己的一份数据</p>
<p><strong>温馨小贴士：关于threadlocal</strong></p>
<p>如果小伙伴们看过threadLocal的源码，你会发现在threadLocal中，无论是他的put方法和他的get方法， 都是先从获得当前用户的线程，然后从线程中取出线程的成员变量map，只要线程不一样，map就不一样，所以可以通过这种方式来做到线程隔离</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302018.png" srcset="/img/loading.gif" lazyload alt="1653068874258"></p>
<p>拦截器代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LoginInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">HandlerInterceptor</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>       <span class="hljs-comment">//1.获取session</span><br>        <span class="hljs-type">HttpSession</span> <span class="hljs-variable">session</span> <span class="hljs-operator">=</span> request.getSession();<br>        <span class="hljs-comment">//2.获取session中的用户</span><br>        <span class="hljs-type">Object</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> session.getAttribute(<span class="hljs-string">&quot;user&quot;</span>);<br>        <span class="hljs-comment">//3.判断用户是否存在</span><br>        <span class="hljs-keyword">if</span>(user == <span class="hljs-literal">null</span>)&#123;<br>              <span class="hljs-comment">//4.不存在，拦截，返回401状态码</span><br>              response.setStatus(<span class="hljs-number">401</span>);<br>              <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>        &#125;<br>        <span class="hljs-comment">//5.存在，保存用户信息到Threadlocal</span><br>        UserHolder.saveUser((User)user);<br>        <span class="hljs-comment">//6.放行</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>让拦截器生效</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MvcConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">WebMvcConfigurer</span> &#123;<br><br>    <span class="hljs-meta">@Resource</span><br>    <span class="hljs-keyword">private</span> StringRedisTemplate stringRedisTemplate;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addInterceptors</span><span class="hljs-params">(InterceptorRegistry registry)</span> &#123;<br>        <span class="hljs-comment">// 登录拦截器</span><br>        registry.addInterceptor(<span class="hljs-keyword">new</span> <span class="hljs-title class_">LoginInterceptor</span>())<br>                .excludePathPatterns(<br>                        <span class="hljs-string">&quot;/shop/**&quot;</span>,<br>                        <span class="hljs-string">&quot;/voucher/**&quot;</span>,<br>                        <span class="hljs-string">&quot;/shop-type/**&quot;</span>,<br>                        <span class="hljs-string">&quot;/upload/**&quot;</span>,<br>                        <span class="hljs-string">&quot;/blog/hot&quot;</span>,<br>                        <span class="hljs-string">&quot;/user/code&quot;</span>,<br>                        <span class="hljs-string">&quot;/user/login&quot;</span><br>                ).order(<span class="hljs-number">1</span>);<br>        <span class="hljs-comment">// token刷新的拦截器</span><br>        registry.addInterceptor(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RefreshTokenInterceptor</span>(stringRedisTemplate)).addPathPatterns(<span class="hljs-string">&quot;/**&quot;</span>).order(<span class="hljs-number">0</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-5、隐藏用户敏感信息"><a href="#1-5、隐藏用户敏感信息" class="headerlink" title="1.5、隐藏用户敏感信息"></a>1.5、隐藏用户敏感信息</h3><p>我们通过浏览器观察到此时用户的全部信息都在，这样极为不靠谱，所以我们应当在返回用户信息之前，将用户的敏感信息进行隐藏，采用的核心思路就是书写一个UserDto对象，这个UserDto对象就没有敏感信息了，我们在返回前，将有用户敏感信息的User对象转化成没有敏感信息的UserDto对象，那么就能够避免这个尴尬的问题了</p>
<p><strong>在登录方法处修改</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//7.保存用户信息到session中</span><br>session.setAttribute(<span class="hljs-string">&quot;user&quot;</span>, BeanUtils.copyProperties(user,UserDTO.class));<br></code></pre></td></tr></table></figure>

<p><strong>在拦截器处：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//5.存在，保存用户信息到Threadlocal</span><br>UserHolder.saveUser((UserDTO) user);<br></code></pre></td></tr></table></figure>

<p><strong>在UserHolder处：将user对象换成UserDTO</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserHolder</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> ThreadLocal&lt;UserDTO&gt; tl = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ThreadLocal</span>&lt;&gt;();<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">saveUser</span><span class="hljs-params">(UserDTO user)</span>&#123;<br>        tl.set(user);<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> UserDTO <span class="hljs-title function_">getUser</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> tl.get();<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">removeUser</span><span class="hljs-params">()</span>&#123;<br>        tl.remove();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-6、session共享问题"><a href="#1-6、session共享问题" class="headerlink" title="1.6、session共享问题"></a>1.6、session共享问题</h3><p><strong>核心思路分析：</strong></p>
<p>每个tomcat中都有一份属于自己的session,假设用户第一次访问第一台tomcat，并且把自己的信息存放到第一台服务器的session中，但是第二次这个用户访问到了第二台tomcat，那么在第二台服务器上，肯定没有第一台服务器存放的session，所以此时 整个登录拦截功能就会出现问题，我们能如何解决这个问题呢？早期的方案是session拷贝，就是说虽然每个tomcat上都有不同的session，但是每当任意一台服务器的session修改时，都会同步给其他的Tomcat服务器的session，这样的话，就可以实现session的共享了</p>
<p>但是这种方案具有两个大问题</p>
<p>1、每台服务器中都有完整的一份session数据，服务器压力过大。</p>
<p>2、session拷贝数据时，可能会出现延迟</p>
<p>所以咱们后来采用的方案都是基于redis来完成，我们把session换成redis，redis数据本身就是共享的，就可以避免session共享的问题了</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302019.png" srcset="/img/loading.gif" lazyload alt="1653069893050"></p>
<h3 id="1-7-Redis代替session的业务流程"><a href="#1-7-Redis代替session的业务流程" class="headerlink" title="1.7 Redis代替session的业务流程"></a>1.7 Redis代替session的业务流程</h3><h4 id="1-7-1、设计key的结构"><a href="#1-7-1、设计key的结构" class="headerlink" title="1.7.1、设计key的结构"></a>1.7.1、设计key的结构</h4><p>首先我们要思考一下利用redis来存储数据，那么到底使用哪种结构呢？由于存入的数据比较简单，我们可以考虑使用String，或者是使用哈希，如下图，如果使用String，同学们注意他的value，用多占用一点空间，如果使用哈希，则他的value中只会存储他数据本身，如果不是特别在意内存，其实使用String就可以啦。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302020.png" srcset="/img/loading.gif" lazyload alt="1653319261433"></p>
<h4 id="1-7-2、设计key的具体细节"><a href="#1-7-2、设计key的具体细节" class="headerlink" title="1.7.2、设计key的具体细节"></a>1.7.2、设计key的具体细节</h4><p>所以我们可以使用String结构，就是一个简单的key，value键值对的方式，但是关于key的处理，session他是每个用户都有自己的session，但是redis的key是共享的，咱们就不能使用code了</p>
<p>在设计这个key的时候，我们之前讲过需要满足两点</p>
<p>1、key要具有唯一性</p>
<p>2、key要方便携带</p>
<p>如果我们采用phone：手机号这个的数据来存储当然是可以的，但是如果把这样的敏感数据存储到redis中并且从页面中带过来毕竟不太合适，所以我们在后台生成一个随机串token，然后让前端带来这个token就能完成我们的整体逻辑了</p>
<h4 id="1-7-3、整体访问流程"><a href="#1-7-3、整体访问流程" class="headerlink" title="1.7.3、整体访问流程"></a>1.7.3、整体访问流程</h4><p>当注册完成后，用户去登录会去校验用户提交的手机号和验证码，是否一致，如果一致，则根据手机号查询用户信息，不存在则新建，最后将用户数据保存到redis，并且生成token作为redis的key，当我们校验用户是否登录时，会去携带着token进行访问，从redis中取出token对应的value，判断是否存在这个数据，如果没有则拦截，如果存在则将其保存到threadLocal中，并且放行。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302021.png" srcset="/img/loading.gif" lazyload alt="1653319474181"></p>
<h3 id="1-8-基于Redis实现短信登录"><a href="#1-8-基于Redis实现短信登录" class="headerlink" title="1.8 基于Redis实现短信登录"></a>1.8 基于Redis实现短信登录</h3><p>这里具体逻辑就不分析了，之前咱们已经重点分析过这个逻辑啦。</p>
<p><strong>UserServiceImpl代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">login</span><span class="hljs-params">(LoginFormDTO loginForm, HttpSession session)</span> &#123;<br>    <span class="hljs-comment">// 1.校验手机号</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">phone</span> <span class="hljs-operator">=</span> loginForm.getPhone();<br>    <span class="hljs-keyword">if</span> (RegexUtils.isPhoneInvalid(phone)) &#123;<br>        <span class="hljs-comment">// 2.如果不符合，返回错误信息</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;手机号格式错误！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.从redis获取验证码并校验</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">cacheCode</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);<br>    <span class="hljs-type">String</span> <span class="hljs-variable">code</span> <span class="hljs-operator">=</span> loginForm.getCode();<br>    <span class="hljs-keyword">if</span> (cacheCode == <span class="hljs-literal">null</span> || !cacheCode.equals(code)) &#123;<br>        <span class="hljs-comment">// 不一致，报错</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;验证码错误&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-comment">// 4.一致，根据手机号查询用户 select * from tb_user where phone = ?</span><br>    <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;phone&quot;</span>, phone).one();<br><br>    <span class="hljs-comment">// 5.判断用户是否存在</span><br>    <span class="hljs-keyword">if</span> (user == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-comment">// 6.不存在，创建新用户并保存</span><br>        user = createUserWithPhone(phone);<br>    &#125;<br><br>    <span class="hljs-comment">// 7.保存用户信息到 redis中</span><br>    <span class="hljs-comment">// 7.1.随机生成token，作为登录令牌</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">token</span> <span class="hljs-operator">=</span> UUID.randomUUID().toString(<span class="hljs-literal">true</span>);<br>    <span class="hljs-comment">// 7.2.将User对象转为HashMap存储</span><br>    <span class="hljs-type">UserDTO</span> <span class="hljs-variable">userDTO</span> <span class="hljs-operator">=</span> BeanUtil.copyProperties(user, UserDTO.class);<br>    Map&lt;String, Object&gt; userMap = BeanUtil.beanToMap(userDTO, <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;(),<br>            CopyOptions.create()<br>                    .setIgnoreNullValue(<span class="hljs-literal">true</span>)<br>                    .setFieldValueEditor((fieldName, fieldValue) -&gt; fieldValue.toString()));<br>    <span class="hljs-comment">// 7.3.存储</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">tokenKey</span> <span class="hljs-operator">=</span> LOGIN_USER_KEY + token;<br>    stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);<br>    <span class="hljs-comment">// 7.4.设置token有效期</span><br>    stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);<br><br>    <span class="hljs-comment">// 8.返回token</span><br>    <span class="hljs-keyword">return</span> Result.ok(token);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-9-解决状态登录刷新问题"><a href="#1-9-解决状态登录刷新问题" class="headerlink" title="1.9 解决状态登录刷新问题"></a>1.9 解决状态登录刷新问题</h3><h4 id="1-9-1-初始方案思路总结："><a href="#1-9-1-初始方案思路总结：" class="headerlink" title="1.9.1 初始方案思路总结："></a>1.9.1 初始方案思路总结：</h4><p>在这个方案中，他确实可以使用对应路径的拦截，同时刷新登录token令牌的存活时间，但是现在这个拦截器他只是拦截需要被拦截的路径，假设当前用户访问了一些不需要拦截的路径，那么这个拦截器就不会生效，所以此时令牌刷新的动作实际上就不会执行，所以这个方案他是存在问题的</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302022.png" srcset="/img/loading.gif" lazyload alt="1653320822964"></p>
<h4 id="1-9-2-优化方案"><a href="#1-9-2-优化方案" class="headerlink" title="1.9.2 优化方案"></a>1.9.2 优化方案</h4><p>既然之前的拦截器无法对不需要拦截的路径生效，那么我们可以添加一个拦截器，在第一个拦截器中拦截所有的路径，把第二个拦截器做的事情放入到第一个拦截器中，同时刷新令牌，因为第一个拦截器有了threadLocal的数据，所以此时第二个拦截器只需要判断拦截器中的user对象是否存在即可，完成整体刷新功能。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302023.png" srcset="/img/loading.gif" lazyload alt="1653320764547"></p>
<h4 id="1-9-3-代码"><a href="#1-9-3-代码" class="headerlink" title="1.9.3 代码"></a>1.9.3 代码</h4><p><strong>RefreshTokenInterceptor</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RefreshTokenInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">HandlerInterceptor</span> &#123;<br><br>    <span class="hljs-keyword">private</span> StringRedisTemplate stringRedisTemplate;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">RefreshTokenInterceptor</span><span class="hljs-params">(StringRedisTemplate stringRedisTemplate)</span> &#123;<br>        <span class="hljs-built_in">this</span>.stringRedisTemplate = stringRedisTemplate;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// 1.获取请求头中的token</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">token</span> <span class="hljs-operator">=</span> request.getHeader(<span class="hljs-string">&quot;authorization&quot;</span>);<br>        <span class="hljs-keyword">if</span> (StrUtil.isBlank(token)) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>        &#125;<br>        <span class="hljs-comment">// 2.基于TOKEN获取redis中的用户</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span>  <span class="hljs-operator">=</span> LOGIN_USER_KEY + token;<br>        Map&lt;Object, Object&gt; userMap = stringRedisTemplate.opsForHash().entries(key);<br>        <span class="hljs-comment">// 3.判断用户是否存在</span><br>        <span class="hljs-keyword">if</span> (userMap.isEmpty()) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>        &#125;<br>        <span class="hljs-comment">// 5.将查询到的hash数据转为UserDTO</span><br>        <span class="hljs-type">UserDTO</span> <span class="hljs-variable">userDTO</span> <span class="hljs-operator">=</span> BeanUtil.fillBeanWithMap(userMap, <span class="hljs-keyword">new</span> <span class="hljs-title class_">UserDTO</span>(), <span class="hljs-literal">false</span>);<br>        <span class="hljs-comment">// 6.存在，保存用户信息到 ThreadLocal</span><br>        UserHolder.saveUser(userDTO);<br>        <span class="hljs-comment">// 7.刷新token有效期</span><br>        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);<br>        <span class="hljs-comment">// 8.放行</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">afterCompletion</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// 移除用户</span><br>        UserHolder.removeUser();<br>    &#125;<br>&#125;<br>	<br></code></pre></td></tr></table></figure>

<p><strong>LoginInterceptor</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LoginInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">HandlerInterceptor</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// 1.判断是否需要拦截（ThreadLocal中是否有用户）</span><br>        <span class="hljs-keyword">if</span> (UserHolder.getUser() == <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-comment">// 没有，需要拦截，设置状态码</span><br>            response.setStatus(<span class="hljs-number">401</span>);<br>            <span class="hljs-comment">// 拦截</span><br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>        &#125;<br>        <span class="hljs-comment">// 有用户，则放行</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="2、商户查询缓存"><a href="#2、商户查询缓存" class="headerlink" title="2、商户查询缓存"></a>2、商户查询缓存</h2><h3 id="2-1-什么是缓存"><a href="#2-1-什么是缓存" class="headerlink" title="2.1 什么是缓存?"></a>2.1 什么是缓存?</h3><p><strong>前言</strong>:<strong>什么是缓存?</strong></p>
<p>就像自行车,越野车的避震器<img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302024.gif" srcset="/img/loading.gif" lazyload></p>
<p>举个例子:越野车,山地自行车,都拥有”避震器”,<strong>防止</strong>车体加速后因惯性,在酷似”U”字母的地形上飞跃,硬着陆导致的<strong>损害</strong>,像个弹簧一样;</p>
<p>同样,实际开发中,系统也需要”避震器”,防止过高的数据访问猛冲系统,导致其操作线程无法及时处理信息而瘫痪;</p>
<p>这在实际开发中对企业讲,对产品口碑,用户评价都是致命的;所以企业非常重视缓存技术;</p>
<p><strong>缓存(<strong>Cache),就是数据交换的</strong>缓冲区</strong>,俗称的缓存就是<strong>缓冲区内的数据</strong>,一般从数据库中获取,存储于本地代码(例如:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">例<span class="hljs-number">1</span>:Static <span class="hljs-keyword">final</span> ConcurrentHashMap&lt;K,V&gt; map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcurrentHashMap</span>&lt;&gt;(); 本地用于高并发<br><br>例<span class="hljs-number">2</span>:<span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Cache&lt;K,V&gt; USER_CACHE = CacheBuilder.newBuilder().build(); 用于redis等缓存<br><br>例<span class="hljs-number">3</span>:Static <span class="hljs-keyword">final</span> Map&lt;K,V&gt; map =  <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>(); 本地缓存<br></code></pre></td></tr></table></figure>

<p>由于其被<strong>Static</strong>修饰,所以随着类的加载而被加载到<strong>内存之中</strong>,作为本地缓存,由于其又被<strong>final</strong>修饰,所以其引用(例3:map)和对象(例3:new HashMap())之间的关系是固定的,不能改变,因此不用担心赋值(&#x3D;)导致缓存失效;</p>
<h4 id="2-1-1-为什么要使用缓存"><a href="#2-1-1-为什么要使用缓存" class="headerlink" title="2.1.1 为什么要使用缓存"></a>2.1.1 为什么要使用缓存</h4><p>一句话:因为<strong>速度快,好用</strong></p>
<p>缓存数据存储于代码中,而代码运行在内存中,内存的读写性能远高于磁盘,缓存可以大大降低<strong>用户访问并发量带来的</strong>服务器读写压力</p>
<p>实际开发过程中,企业的数据量,少则几十万,多则几千万,这么大数据量,如果没有缓存来作为”避震器”,系统是几乎撑不住的,所以企业会大量运用到缓存技术;</p>
<p>但是缓存也会增加代码复杂度和运营的成本:</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302025.png" srcset="/img/loading.gif" lazyload></p>
<h4 id="2-1-2-如何使用缓存"><a href="#2-1-2-如何使用缓存" class="headerlink" title="2.1.2 如何使用缓存"></a>2.1.2 如何使用缓存</h4><p>实际开发中,会构筑多级缓存来使系统运行速度进一步提升,例如:本地缓存与redis中的缓存并发使用</p>
<p><strong>浏览器缓存</strong>：主要是存在于浏览器端的缓存</p>
<p><strong>应用层缓存：</strong>可以分为tomcat本地缓存，比如之前提到的map，或者是使用redis作为缓存</p>
<p><strong>数据库缓存：</strong>在数据库中有一片空间是 buffer pool，增改查数据都会先加载到mysql的缓存中</p>
<p><strong>CPU缓存：</strong>当代计算机最大的问题是 cpu性能提升了，但内存读写速度没有跟上，所以为了适应当下的情况，增加了cpu的L1，L2，L3级的缓存</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302026.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="2-2-添加商户缓存"><a href="#2-2-添加商户缓存" class="headerlink" title="2.2 添加商户缓存"></a>2.2 添加商户缓存</h3><p>在我们查询商户信息时，我们是直接操作从数据库中去进行查询的，大致逻辑是这样，直接查询数据库那肯定慢咯，所以我们需要增加缓存</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs less"><span class="hljs-variable">@GetMapping</span>(<span class="hljs-string">&quot;/&#123;id&#125;&quot;</span>)<br>public Result <span class="hljs-built_in">queryShopById</span>(<span class="hljs-variable">@PathVariable</span>(<span class="hljs-string">&quot;id&quot;</span>) Long id) &#123;<br>    <span class="hljs-comment">//这里是直接查询数据库</span><br>    <span class="hljs-selector-tag">return</span> <span class="hljs-selector-tag">shopService</span><span class="hljs-selector-class">.queryById</span>(id);<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="2-2-1-、缓存模型和思路"><a href="#2-2-1-、缓存模型和思路" class="headerlink" title="2.2.1 、缓存模型和思路"></a>2.2.1 、缓存模型和思路</h4><p>标准的操作方式就是查询数据库之前先查询缓存，如果缓存数据存在，则直接从缓存中返回，如果缓存数据不存在，再查询数据库，然后将数据存入redis。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302027.png" srcset="/img/loading.gif" lazyload alt="1653322097736"></p>
<h4 id="2-1-2、代码如下"><a href="#2-1-2、代码如下" class="headerlink" title="2.1.2、代码如下"></a>2.1.2、代码如下</h4><p>代码思路：如果缓存有，则直接返回，如果缓存不存在，则查询数据库，然后存入redis。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302028.png" srcset="/img/loading.gif" lazyload alt="1653322190155"></p>
<h3 id="2-3-缓存更新策略"><a href="#2-3-缓存更新策略" class="headerlink" title="2.3 缓存更新策略"></a>2.3 缓存更新策略</h3><p>缓存更新是redis为了节约内存而设计出来的一个东西，主要是因为内存数据宝贵，当我们向redis插入太多数据，此时就可能会导致缓存中的数据过多，所以redis会对部分数据进行更新，或者把他叫为淘汰更合适。</p>
<p><strong>内存淘汰：</strong>redis自动进行，当redis内存达到咱们设定的max-memery的时候，会自动触发淘汰机制，淘汰掉一些不重要的数据(可以自己设置策略方式)</p>
<p><strong>超时剔除：</strong>当我们给redis设置了过期时间ttl之后，redis会将超时的数据进行删除，方便咱们继续使用缓存</p>
<p><strong>主动更新：</strong>我们可以手动调用方法把缓存删掉，通常用于解决缓存和数据库不一致问题</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302029.png" srcset="/img/loading.gif" lazyload alt="1653322506393"></p>
<h4 id="2-3-1-、数据库缓存不一致解决方案："><a href="#2-3-1-、数据库缓存不一致解决方案：" class="headerlink" title="2.3.1 、数据库缓存不一致解决方案："></a>2.3.1 、数据库缓存不一致解决方案：</h4><p>由于我们的<strong>缓存的数据源来自于数据库</strong>,而数据库的<strong>数据是会发生变化的</strong>,因此,如果当数据库中<strong>数据发生变化,而缓存却没有同步</strong>,此时就会有<strong>一致性问题存在</strong>,其后果是:</p>
<p>用户使用缓存中的过时数据,就会产生类似多线程数据安全问题,从而影响业务,产品口碑等;怎么解决呢？有如下几种方案</p>
<p>Cache Aside Pattern 人工编码方式：缓存调用者在更新完数据库后再去更新缓存，也称之为双写方案</p>
<p>Read&#x2F;Write Through Pattern : 由系统本身完成，数据库与缓存的问题交由系统本身去处理</p>
<p>Write Behind Caching Pattern ：调用者只操作缓存，其他线程去异步处理数据库，实现最终一致</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302030.png" srcset="/img/loading.gif" lazyload alt="1653322857620"></p>
<h4 id="2-3-2-、数据库和缓存不一致采用什么方案"><a href="#2-3-2-、数据库和缓存不一致采用什么方案" class="headerlink" title="2.3.2 、数据库和缓存不一致采用什么方案"></a>2.3.2 、数据库和缓存不一致采用什么方案</h4><p>综合考虑使用方案一，但是方案一调用者如何处理呢？这里有几个问题</p>
<p>操作缓存和数据库时有三个问题需要考虑：</p>
<p>如果采用第一个方案，那么假设我们每次操作数据库后，都操作缓存，但是中间如果没有人查询，那么这个更新动作实际上只有最后一次生效，中间的更新动作意义并不大，我们可以把缓存删除，等待再次查询时，将缓存中的数据加载出来</p>
<ul>
<li><p>删除缓存还是更新缓存？</p>
<ul>
<li>更新缓存：每次更新数据库都更新缓存，无效写操作较多</li>
<li>删除缓存：更新数据库时让缓存失效，查询时再更新缓存</li>
</ul>
</li>
<li><p>如何保证缓存与数据库的操作的同时成功或失败？</p>
<ul>
<li>单体系统，将缓存与数据库操作放在一个事务</li>
<li>分布式系统，利用TCC等分布式事务方案</li>
</ul>
</li>
</ul>
<p>应该具体操作缓存还是操作数据库，我们应当是先操作数据库，再删除缓存，原因在于，如果你选择第一种方案，在两个线程并发来访问时，假设线程1先来，他先把缓存删了，此时线程2过来，他查询缓存数据并不存在，此时他写入缓存，当他写入缓存后，线程1再执行更新动作时，实际上写入的就是旧的数据，新的数据被旧数据覆盖了。</p>
<ul>
<li>先操作缓存还是先操作数据库？<ul>
<li>先删除缓存，再操作数据库</li>
<li>先操作数据库，再删除缓存</li>
</ul>
</li>
</ul>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302031.png" srcset="/img/loading.gif" lazyload alt="1653323595206"></p>
<h3 id="2-4-实现商铺和缓存与数据库双写一致"><a href="#2-4-实现商铺和缓存与数据库双写一致" class="headerlink" title="2.4 实现商铺和缓存与数据库双写一致"></a>2.4 实现商铺和缓存与数据库双写一致</h3><p>核心思路如下：</p>
<p>修改ShopController中的业务逻辑，满足下面的需求：</p>
<p>根据id查询店铺时，如果缓存未命中，则查询数据库，将数据库结果写入缓存，并设置超时时间</p>
<p>根据id修改店铺时，先修改数据库，再删除缓存</p>
<p><strong>修改重点代码1</strong>：修改<strong>ShopServiceImpl</strong>的queryById方法</p>
<p><strong>设置redis缓存时添加过期时间</strong></p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302032.png" srcset="/img/loading.gif" lazyload alt="1653325871232"></p>
<p><strong>修改重点代码2</strong></p>
<p>代码分析：通过之前的淘汰，我们确定了采用删除策略，来解决双写问题，当我们修改了数据之后，然后把缓存中的数据进行删除，查询时发现缓存中没有数据，则会从mysql中加载最新的数据，从而避免数据库和缓存不一致的问题</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302033.png" srcset="/img/loading.gif" lazyload alt="1653325929549"></p>
<h3 id="2-5-缓存穿透问题的解决思路"><a href="#2-5-缓存穿透问题的解决思路" class="headerlink" title="2.5 缓存穿透问题的解决思路"></a>2.5 缓存穿透问题的解决思路</h3><p>缓存穿透 ：缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在，这样缓存永远不会生效，这些请求都会打到数据库。</p>
<p>常见的解决方案有两种：</p>
<ul>
<li>缓存空对象<ul>
<li>优点：实现简单，维护方便</li>
<li>缺点：<ul>
<li>额外的内存消耗</li>
<li>可能造成短期的不一致</li>
</ul>
</li>
</ul>
</li>
<li>布隆过滤<ul>
<li>优点：内存占用较少，没有多余key</li>
<li>缺点：<ul>
<li>实现复杂</li>
<li>存在误判可能</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><strong>缓存空对象思路分析：</strong>当我们客户端访问不存在的数据时，先请求redis，但是此时redis中没有数据，此时会访问到数据库，但是数据库中也没有数据，这个数据穿透了缓存，直击数据库，我们都知道数据库能够承载的并发不如redis这么高，如果大量的请求同时过来访问这种不存在的数据，这些请求就都会访问到数据库，简单的解决方案就是哪怕这个数据在数据库中也不存在，我们也把这个数据存入到redis中去，这样，下次用户过来访问这个不存在的数据，那么在redis中也能找到这个数据就不会进入到缓存了</p>
<p><strong>布隆过滤：</strong>布隆过滤器其实采用的是哈希思想来解决这个问题，通过一个庞大的二进制数组，走哈希思想去判断当前这个要查询的这个数据是否存在，如果布隆过滤器判断存在，则放行，这个请求会去访问redis，哪怕此时redis中的数据过期了，但是数据库中一定存在这个数据，在数据库中查询出来这个数据后，再将其放入到redis中，</p>
<p>假设布隆过滤器判断这个数据不存在，则直接返回</p>
<p>这种方式优点在于节约内存空间，存在误判，误判原因在于：布隆过滤器走的是哈希思想，只要哈希思想，就可能存在哈希冲突</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302035.png" srcset="/img/loading.gif" lazyload alt="1653326156516"></p>
<h3 id="2-6-编码解决商品查询的缓存穿透问题："><a href="#2-6-编码解决商品查询的缓存穿透问题：" class="headerlink" title="2.6 编码解决商品查询的缓存穿透问题："></a>2.6 编码解决商品查询的缓存穿透问题：</h3><p>核心思路如下：</p>
<p>在原来的逻辑中，我们如果发现这个数据在mysql中不存在，直接就返回404了，这样是会存在缓存穿透问题的</p>
<p>现在的逻辑中：如果这个数据不存在，我们不会返回404 ，还是会把这个数据写入到Redis中，并且将value设置为空，欧当再次发起查询时，我们如果发现命中之后，判断这个value是否是null，如果是null，则是之前写入的数据，证明是缓存穿透数据，如果不是，则直接返回数据。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302036.png" srcset="/img/loading.gif" lazyload alt="1653327124561"></p>
<p><strong>小总结：</strong></p>
<p>缓存穿透产生的原因是什么？</p>
<ul>
<li>用户请求的数据在缓存中和数据库中都不存在，不断发起这样的请求，给数据库带来巨大压力</li>
</ul>
<p>缓存穿透的解决方案有哪些？</p>
<ul>
<li>缓存null值</li>
<li>布隆过滤</li>
<li>增强id的复杂度，避免被猜测id规律</li>
<li>做好数据的基础格式校验</li>
<li>加强用户权限校验</li>
<li>做好热点参数的限流</li>
</ul>
<h3 id="2-7-缓存雪崩问题及解决思路"><a href="#2-7-缓存雪崩问题及解决思路" class="headerlink" title="2.7 缓存雪崩问题及解决思路"></a>2.7 缓存雪崩问题及解决思路</h3><p>缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机，导致大量请求到达数据库，带来巨大压力。</p>
<p>解决方案：</p>
<ul>
<li>给不同的Key的TTL添加随机值</li>
<li>利用Redis集群提高服务的可用性</li>
<li>给缓存业务添加降级限流策略</li>
<li>给业务添加多级缓存</li>
</ul>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302037.png" srcset="/img/loading.gif" lazyload alt="1653327884526"></p>
<h3 id="2-8-缓存击穿问题及解决思路"><a href="#2-8-缓存击穿问题及解决思路" class="headerlink" title="2.8 缓存击穿问题及解决思路"></a>2.8 缓存击穿问题及解决思路</h3><p>缓存击穿问题也叫热点Key问题，就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了，无数的请求访问会在瞬间给数据库带来巨大的冲击。</p>
<p>常见的解决方案有两种：</p>
<ul>
<li>互斥锁</li>
<li>逻辑过期</li>
</ul>
<p>逻辑分析：假设线程1在查询缓存之后，本来应该去查询数据库，然后把这个数据重新加载到缓存的，此时只要线程1走完这个逻辑，其他线程就都能从缓存中加载这些数据了，但是假设在线程1没有走完的时候，后续的线程2，线程3，线程4同时过来访问当前这个方法， 那么这些线程都不能从缓存中查询到数据，那么他们就会同一时刻来访问查询缓存，都没查到，接着同一时间去访问数据库，同时的去执行数据库代码，对数据库访问压力过大</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302038.png" srcset="/img/loading.gif" lazyload alt="1653328022622"></p>
<p>解决方案一、使用锁来解决：</p>
<p>因为锁能实现互斥性。假设线程过来，只能一个人一个人的来访问数据库，从而避免对于数据库访问压力过大，但这也会影响查询的性能，因为此时会让查询的性能从并行变成了串行，我们可以采用tryLock方法 + double check来解决这样的问题。</p>
<p>假设现在线程1过来访问，他查询缓存没有命中，但是此时他获得到了锁的资源，那么线程1就会一个人去执行逻辑，假设现在线程2过来，线程2在执行过程中，并没有获得到锁，那么线程2就可以进行到休眠，直到线程1把锁释放后，线程2获得到锁，然后再来执行逻辑，此时就能够从缓存中拿到数据了。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302039.png" srcset="/img/loading.gif" lazyload alt="1653328288627"></p>
<p>解决方案二、逻辑过期方案</p>
<p>方案分析：我们之所以会出现这个缓存击穿问题，主要原因是在于我们对key设置了过期时间，假设我们不设置过期时间，其实就不会有缓存击穿的问题，但是不设置过期时间，这样数据不就一直占用我们内存了吗，我们可以采用逻辑过期方案。</p>
<p>我们把过期时间设置在 redis的value中，注意：这个过期时间并不会直接作用于redis，而是我们后续通过逻辑去处理。假设线程1去查询缓存，然后从value中判断出来当前的数据已经过期了，此时线程1去获得互斥锁，那么其他线程会进行阻塞，获得了锁的线程他会开启一个 线程去进行 以前的重构数据的逻辑，直到新开的线程完成这个逻辑后，才释放锁， 而线程1直接进行返回，假设现在线程3过来访问，由于线程线程2持有着锁，所以线程3无法获得锁，线程3也直接返回数据，只有等到新开的线程2把重建数据构建完后，其他线程才能走返回正确的数据。</p>
<p>这种方案巧妙在于，异步的构建缓存，缺点在于在构建完缓存之前，返回的都是脏数据。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302040.png" srcset="/img/loading.gif" lazyload alt="1653328663897"></p>
<p>进行对比</p>
<p><strong>互斥锁方案：</strong>由于保证了互斥性，所以数据一致，且实现简单，因为仅仅只需要加一把锁而已，也没其他的事情需要操心，所以没有额外的内存消耗，缺点在于有锁就有死锁问题的发生，且只能串行执行性能肯定受到影响</p>
<p><strong>逻辑过期方案：</strong> 线程读取过程中不需要等待，性能好，有一个额外的线程持有锁去进行重构数据，但是在重构数据完成前，其他的线程只能返回之前的数据，且实现起来麻烦</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302041.png" srcset="/img/loading.gif" lazyload alt="1653357522914"></p>
<h3 id="2-9-利用互斥锁解决缓存击穿问题"><a href="#2-9-利用互斥锁解决缓存击穿问题" class="headerlink" title="2.9 利用互斥锁解决缓存击穿问题"></a>2.9 利用互斥锁解决缓存击穿问题</h3><p>核心思路：相较于原来从缓存中查询不到数据后直接查询数据库而言，现在的方案是 进行查询之后，如果从缓存没有查询到数据，则进行互斥锁的获取，获取互斥锁后，判断是否获得到了锁，如果没有获得到，则休眠，过一会再进行尝试，直到获取到锁为止，才能进行查询</p>
<p>如果获取到了锁的线程，再去进行查询，查询后将数据写入redis，再释放锁，返回数据，利用互斥锁就能保证只有一个线程去执行操作数据库的逻辑，防止缓存击穿</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302042.png" srcset="/img/loading.gif" lazyload alt="1653357860001"></p>
<p><strong>操作锁的代码：</strong></p>
<p>核心思路就是利用redis的setnx方法来表示获取锁，该方法含义是redis中如果没有这个key，则插入成功，返回1，在stringRedisTemplate中返回true，  如果有这个key则插入失败，则返回0，在stringRedisTemplate返回false，我们可以通过true，或者是false，来表示是否有线程成功插入key，成功插入的key的线程我们认为他就是获得到锁的线程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><span class="hljs-keyword">private</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">tryLock</span><span class="hljs-params">(String key)</span> &#123;<br>    <span class="hljs-type">Boolean</span> <span class="hljs-variable">flag</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().setIfAbsent(key, <span class="hljs-string">&quot;1&quot;</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS);<br>    <span class="hljs-keyword">return</span> BooleanUtil.isTrue(flag);<br>&#125;<br><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">(String key)</span> &#123;<br>    stringRedisTemplate.delete(key);<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>操作代码：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> Shop <span class="hljs-title function_">queryWithMutex</span><span class="hljs-params">(Long id)</span>  &#123;<br>       <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> CACHE_SHOP_KEY + id;<br>       <span class="hljs-comment">// 1、从redis中查询商铺缓存</span><br>       <span class="hljs-type">String</span> <span class="hljs-variable">shopJson</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(<span class="hljs-string">&quot;key&quot;</span>);<br>       <span class="hljs-comment">// 2、判断是否存在</span><br>       <span class="hljs-keyword">if</span> (StrUtil.isNotBlank(shopJson)) &#123;<br>           <span class="hljs-comment">// 存在,直接返回</span><br>           <span class="hljs-keyword">return</span> JSONUtil.toBean(shopJson, Shop.class);<br>       &#125;<br>       <span class="hljs-comment">//判断命中的值是否是空值</span><br>       <span class="hljs-keyword">if</span> (shopJson != <span class="hljs-literal">null</span>) &#123;<br>           <span class="hljs-comment">//返回一个错误信息</span><br>           <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>       &#125;<br>       <span class="hljs-comment">// 4.实现缓存重构</span><br>       <span class="hljs-comment">//4.1 获取互斥锁</span><br>       <span class="hljs-type">String</span> <span class="hljs-variable">lockKey</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;lock:shop:&quot;</span> + id;<br>       <span class="hljs-type">Shop</span> <span class="hljs-variable">shop</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>       <span class="hljs-keyword">try</span> &#123;<br>           <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> tryLock(lockKey);<br>           <span class="hljs-comment">// 4.2 判断否获取成功</span><br>           <span class="hljs-keyword">if</span>(!isLock)&#123;<br>               <span class="hljs-comment">//4.3 失败，则休眠重试</span><br>               Thread.sleep(<span class="hljs-number">50</span>);<br>               <span class="hljs-keyword">return</span> queryWithMutex(id);<br>           &#125;<br>           <span class="hljs-comment">//4.4 成功，根据id查询数据库</span><br>            shop = getById(id);<br>           <span class="hljs-comment">// 5.不存在，返回错误</span><br>           <span class="hljs-keyword">if</span>(shop == <span class="hljs-literal">null</span>)&#123;<br>                <span class="hljs-comment">//将空值写入redis</span><br>               stringRedisTemplate.opsForValue().set(key,<span class="hljs-string">&quot;&quot;</span>,CACHE_NULL_TTL,TimeUnit.MINUTES);<br>               <span class="hljs-comment">//返回错误信息</span><br>               <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>           &#125;<br>           <span class="hljs-comment">//6.写入redis</span><br>           stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_NULL_TTL,TimeUnit.MINUTES);<br><br>       &#125;<span class="hljs-keyword">catch</span> (Exception e)&#123;<br>           <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>       &#125;<br>       <span class="hljs-keyword">finally</span> &#123;<br>           <span class="hljs-comment">//7.释放互斥锁</span><br>           unlock(lockKey);<br>       &#125;<br>       <span class="hljs-keyword">return</span> shop;<br>   &#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-0-、利用逻辑过期解决缓存击穿问题"><a href="#3-0-、利用逻辑过期解决缓存击穿问题" class="headerlink" title="3.0 、利用逻辑过期解决缓存击穿问题"></a>3.0 、利用逻辑过期解决缓存击穿问题</h3><p><strong>需求：修改根据id查询商铺的业务，基于逻辑过期方式来解决缓存击穿问题</strong></p>
<p>思路分析：当用户开始查询redis时，判断是否命中，如果没有命中则直接返回空数据，不查询数据库，而一旦命中后，将value取出，判断value中的过期时间是否满足，如果没有过期，则直接返回redis中的数据，如果过期，则在开启独立线程后直接返回之前的数据，独立线程去重构数据，重构完成后释放互斥锁。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302043.png" srcset="/img/loading.gif" lazyload alt="1653360308731"></p>
<p>如果封装数据：因为现在redis中存储的数据的value需要带上过期时间，此时要么你去修改原来的实体类，要么你</p>
<p><strong>步骤一、</strong></p>
<p>新建一个实体类，我们采用第二个方案，这个方案，对原来代码没有侵入性。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-meta">@Data</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedisData</span> &#123;<br>    <span class="hljs-keyword">private</span> LocalDateTime expireTime;<br>    <span class="hljs-keyword">private</span> Object <span class="hljs-keyword">data</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>步骤二、</strong></p>
<p>在<strong>ShopServiceImpl</strong> 新增此方法，利用单元测试进行缓存预热</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302044.png" srcset="/img/loading.gif" lazyload alt="1653360807133"></p>
<p><strong>在测试类中</strong></p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302045.png" srcset="/img/loading.gif" lazyload alt="1653360864839"></p>
<p>步骤三：正式代码</p>
<p><strong>ShopServiceImpl</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">ExecutorService</span> <span class="hljs-variable">CACHE_REBUILD_EXECUTOR</span> <span class="hljs-operator">=</span> Executors.newFixedThreadPool(<span class="hljs-number">10</span>);<br><span class="hljs-keyword">public</span> Shop <span class="hljs-title function_">queryWithLogicalExpire</span><span class="hljs-params">( Long id )</span> &#123;<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> CACHE_SHOP_KEY + id;<br>    <span class="hljs-comment">// 1.从redis查询商铺缓存</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">json</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(key);<br>    <span class="hljs-comment">// 2.判断是否存在</span><br>    <span class="hljs-keyword">if</span> (StrUtil.isBlank(json)) &#123;<br>        <span class="hljs-comment">// 3.存在，直接返回</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>    <span class="hljs-comment">// 4.命中，需要先把json反序列化为对象</span><br>    <span class="hljs-type">RedisData</span> <span class="hljs-variable">redisData</span> <span class="hljs-operator">=</span> JSONUtil.toBean(json, RedisData.class);<br>    <span class="hljs-type">Shop</span> <span class="hljs-variable">shop</span> <span class="hljs-operator">=</span> JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);<br>    <span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">expireTime</span> <span class="hljs-operator">=</span> redisData.getExpireTime();<br>    <span class="hljs-comment">// 5.判断是否过期</span><br>    <span class="hljs-keyword">if</span>(expireTime.isAfter(LocalDateTime.now())) &#123;<br>        <span class="hljs-comment">// 5.1.未过期，直接返回店铺信息</span><br>        <span class="hljs-keyword">return</span> shop;<br>    &#125;<br>    <span class="hljs-comment">// 5.2.已过期，需要缓存重建</span><br>    <span class="hljs-comment">// 6.缓存重建</span><br>    <span class="hljs-comment">// 6.1.获取互斥锁</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">lockKey</span> <span class="hljs-operator">=</span> LOCK_SHOP_KEY + id;<br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> tryLock(lockKey);<br>    <span class="hljs-comment">// 6.2.判断是否获取锁成功</span><br>    <span class="hljs-keyword">if</span> (isLock)&#123;<br>        CACHE_REBUILD_EXECUTOR.submit( ()-&gt;&#123;<br><br>            <span class="hljs-keyword">try</span>&#123;<br>                <span class="hljs-comment">//重建缓存</span><br>                <span class="hljs-built_in">this</span>.saveShop2Redis(id,<span class="hljs-number">20L</span>);<br>            &#125;<span class="hljs-keyword">catch</span> (Exception e)&#123;<br>                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>            &#125;<span class="hljs-keyword">finally</span> &#123;<br>                unlock(lockKey);<br>            &#125;<br>        &#125;);<br>    &#125;<br>    <span class="hljs-comment">// 6.4.返回过期的商铺信息</span><br>    <span class="hljs-keyword">return</span> shop;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-1、封装Redis工具类"><a href="#3-1、封装Redis工具类" class="headerlink" title="3.1、封装Redis工具类"></a>3.1、封装Redis工具类</h3><p>基于StringRedisTemplate封装一个缓存工具类，满足下列需求：</p>
<ul>
<li>方法1：将任意Java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间</li>
<li>方法2：将任意Java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，用于处理缓</li>
</ul>
<p>存击穿问题</p>
<ul>
<li>方法3：根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透问题</li>
<li>方法4：根据指定的key查询缓存，并反序列化为指定类型，需要利用逻辑过期解决缓存击穿问题</li>
</ul>
<p>将逻辑进行封装</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Slf4j</span><br><span class="hljs-meta">@Component</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CacheClient</span> &#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> StringRedisTemplate stringRedisTemplate;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">ExecutorService</span> <span class="hljs-variable">CACHE_REBUILD_EXECUTOR</span> <span class="hljs-operator">=</span> Executors.newFixedThreadPool(<span class="hljs-number">10</span>);<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">CacheClient</span><span class="hljs-params">(StringRedisTemplate stringRedisTemplate)</span> &#123;<br>        <span class="hljs-built_in">this</span>.stringRedisTemplate = stringRedisTemplate;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">set</span><span class="hljs-params">(String key, Object value, Long time, TimeUnit unit)</span> &#123;<br>        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setWithLogicalExpire</span><span class="hljs-params">(String key, Object value, Long time, TimeUnit unit)</span> &#123;<br>        <span class="hljs-comment">// 设置逻辑过期</span><br>        <span class="hljs-type">RedisData</span> <span class="hljs-variable">redisData</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RedisData</span>();<br>        redisData.setData(value);<br>        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));<br>        <span class="hljs-comment">// 写入Redis</span><br>        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> &lt;R,ID&gt; R <span class="hljs-title function_">queryWithPassThrough</span><span class="hljs-params">(</span><br><span class="hljs-params">            String keyPrefix, ID id, Class&lt;R&gt; type, Function&lt;ID, R&gt; dbFallback, Long time, TimeUnit unit)</span>&#123;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyPrefix + id;<br>        <span class="hljs-comment">// 1.从redis查询商铺缓存</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">json</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(key);<br>        <span class="hljs-comment">// 2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (StrUtil.isNotBlank(json)) &#123;<br>            <span class="hljs-comment">// 3.存在，直接返回</span><br>            <span class="hljs-keyword">return</span> JSONUtil.toBean(json, type);<br>        &#125;<br>        <span class="hljs-comment">// 判断命中的是否是空值</span><br>        <span class="hljs-keyword">if</span> (json != <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-comment">// 返回一个错误信息</span><br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>        &#125;<br><br>        <span class="hljs-comment">// 4.不存在，根据id查询数据库</span><br>        <span class="hljs-type">R</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> dbFallback.apply(id);<br>        <span class="hljs-comment">// 5.不存在，返回错误</span><br>        <span class="hljs-keyword">if</span> (r == <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-comment">// 将空值写入redis</span><br>            stringRedisTemplate.opsForValue().set(key, <span class="hljs-string">&quot;&quot;</span>, CACHE_NULL_TTL, TimeUnit.MINUTES);<br>            <span class="hljs-comment">// 返回错误信息</span><br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>        &#125;<br>        <span class="hljs-comment">// 6.存在，写入redis</span><br>        <span class="hljs-built_in">this</span>.set(key, r, time, unit);<br>        <span class="hljs-keyword">return</span> r;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> &lt;R, ID&gt; R <span class="hljs-title function_">queryWithLogicalExpire</span><span class="hljs-params">(</span><br><span class="hljs-params">            String keyPrefix, ID id, Class&lt;R&gt; type, Function&lt;ID, R&gt; dbFallback, Long time, TimeUnit unit)</span> &#123;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyPrefix + id;<br>        <span class="hljs-comment">// 1.从redis查询商铺缓存</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">json</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(key);<br>        <span class="hljs-comment">// 2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (StrUtil.isBlank(json)) &#123;<br>            <span class="hljs-comment">// 3.存在，直接返回</span><br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>        &#125;<br>        <span class="hljs-comment">// 4.命中，需要先把json反序列化为对象</span><br>        <span class="hljs-type">RedisData</span> <span class="hljs-variable">redisData</span> <span class="hljs-operator">=</span> JSONUtil.toBean(json, RedisData.class);<br>        <span class="hljs-type">R</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> JSONUtil.toBean((JSONObject) redisData.getData(), type);<br>        <span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">expireTime</span> <span class="hljs-operator">=</span> redisData.getExpireTime();<br>        <span class="hljs-comment">// 5.判断是否过期</span><br>        <span class="hljs-keyword">if</span>(expireTime.isAfter(LocalDateTime.now())) &#123;<br>            <span class="hljs-comment">// 5.1.未过期，直接返回店铺信息</span><br>            <span class="hljs-keyword">return</span> r;<br>        &#125;<br>        <span class="hljs-comment">// 5.2.已过期，需要缓存重建</span><br>        <span class="hljs-comment">// 6.缓存重建</span><br>        <span class="hljs-comment">// 6.1.获取互斥锁</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">lockKey</span> <span class="hljs-operator">=</span> LOCK_SHOP_KEY + id;<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> tryLock(lockKey);<br>        <span class="hljs-comment">// 6.2.判断是否获取锁成功</span><br>        <span class="hljs-keyword">if</span> (isLock)&#123;<br>            <span class="hljs-comment">// 6.3.成功，开启独立线程，实现缓存重建</span><br>            CACHE_REBUILD_EXECUTOR.submit(() -&gt; &#123;<br>                <span class="hljs-keyword">try</span> &#123;<br>                    <span class="hljs-comment">// 查询数据库</span><br>                    <span class="hljs-type">R</span> <span class="hljs-variable">newR</span> <span class="hljs-operator">=</span> dbFallback.apply(id);<br>                    <span class="hljs-comment">// 重建缓存</span><br>                    <span class="hljs-built_in">this</span>.setWithLogicalExpire(key, newR, time, unit);<br>                &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>                &#125;<span class="hljs-keyword">finally</span> &#123;<br>                    <span class="hljs-comment">// 释放锁</span><br>                    unlock(lockKey);<br>                &#125;<br>            &#125;);<br>        &#125;<br>        <span class="hljs-comment">// 6.4.返回过期的商铺信息</span><br>        <span class="hljs-keyword">return</span> r;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> &lt;R, ID&gt; R <span class="hljs-title function_">queryWithMutex</span><span class="hljs-params">(</span><br><span class="hljs-params">            String keyPrefix, ID id, Class&lt;R&gt; type, Function&lt;ID, R&gt; dbFallback, Long time, TimeUnit unit)</span> &#123;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyPrefix + id;<br>        <span class="hljs-comment">// 1.从redis查询商铺缓存</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">shopJson</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(key);<br>        <span class="hljs-comment">// 2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (StrUtil.isNotBlank(shopJson)) &#123;<br>            <span class="hljs-comment">// 3.存在，直接返回</span><br>            <span class="hljs-keyword">return</span> JSONUtil.toBean(shopJson, type);<br>        &#125;<br>        <span class="hljs-comment">// 判断命中的是否是空值</span><br>        <span class="hljs-keyword">if</span> (shopJson != <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-comment">// 返回一个错误信息</span><br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>        &#125;<br><br>        <span class="hljs-comment">// 4.实现缓存重建</span><br>        <span class="hljs-comment">// 4.1.获取互斥锁</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">lockKey</span> <span class="hljs-operator">=</span> LOCK_SHOP_KEY + id;<br>        <span class="hljs-type">R</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> tryLock(lockKey);<br>            <span class="hljs-comment">// 4.2.判断是否获取成功</span><br>            <span class="hljs-keyword">if</span> (!isLock) &#123;<br>                <span class="hljs-comment">// 4.3.获取锁失败，休眠并重试</span><br>                Thread.sleep(<span class="hljs-number">50</span>);<br>                <span class="hljs-keyword">return</span> queryWithMutex(keyPrefix, id, type, dbFallback, time, unit);<br>            &#125;<br>            <span class="hljs-comment">// 4.4.获取锁成功，根据id查询数据库</span><br>            r = dbFallback.apply(id);<br>            <span class="hljs-comment">// 5.不存在，返回错误</span><br>            <span class="hljs-keyword">if</span> (r == <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-comment">// 将空值写入redis</span><br>                stringRedisTemplate.opsForValue().set(key, <span class="hljs-string">&quot;&quot;</span>, CACHE_NULL_TTL, TimeUnit.MINUTES);<br>                <span class="hljs-comment">// 返回错误信息</span><br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>            &#125;<br>            <span class="hljs-comment">// 6.存在，写入redis</span><br>            <span class="hljs-built_in">this</span>.set(key, r, time, unit);<br>        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>        &#125;<span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-comment">// 7.释放锁</span><br>            unlock(lockKey);<br>        &#125;<br>        <span class="hljs-comment">// 8.返回</span><br>        <span class="hljs-keyword">return</span> r;<br>    &#125;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">tryLock</span><span class="hljs-params">(String key)</span> &#123;<br>        <span class="hljs-type">Boolean</span> <span class="hljs-variable">flag</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().setIfAbsent(key, <span class="hljs-string">&quot;1&quot;</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS);<br>        <span class="hljs-keyword">return</span> BooleanUtil.isTrue(flag);<br>    &#125;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">(String key)</span> &#123;<br>        stringRedisTemplate.delete(key);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在ShopServiceImpl 中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Resource</span><br><span class="hljs-keyword">private</span> CacheClient cacheClient;<br><br> <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryById</span><span class="hljs-params">(Long id)</span> &#123;<br>        <span class="hljs-comment">// 解决缓存穿透</span><br>        <span class="hljs-type">Shop</span> <span class="hljs-variable">shop</span> <span class="hljs-operator">=</span> cacheClient<br>                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, <span class="hljs-built_in">this</span>::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);<br><br>        <span class="hljs-comment">// 互斥锁解决缓存击穿</span><br>        <span class="hljs-comment">// Shop shop = cacheClient</span><br>        <span class="hljs-comment">//         .queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);</span><br><br>        <span class="hljs-comment">// 逻辑过期解决缓存击穿</span><br>        <span class="hljs-comment">// Shop shop = cacheClient</span><br>        <span class="hljs-comment">//         .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);</span><br><br>        <span class="hljs-keyword">if</span> (shop == <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;店铺不存在！&quot;</span>);<br>        &#125;<br>        <span class="hljs-comment">// 7.返回</span><br>        <span class="hljs-keyword">return</span> Result.ok(shop);<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="3、优惠卷秒杀"><a href="#3、优惠卷秒杀" class="headerlink" title="3、优惠卷秒杀"></a>3、优惠卷秒杀</h2><h3 id="3-1-全局唯一ID"><a href="#3-1-全局唯一ID" class="headerlink" title="3.1 -全局唯一ID"></a>3.1 -全局唯一ID</h3><p>每个店铺都可以发布优惠券：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302046.png" srcset="/img/loading.gif" lazyload alt="1653362612286"></p>
<p>当用户抢购时，就会生成订单并保存到tb_voucher_order这张表中，而订单表如果使用数据库自增ID就存在一些问题：</p>
<ul>
<li>id的规律性太明显</li>
<li>受单表数据量的限制</li>
</ul>
<p>场景分析：如果我们的id具有太明显的规则，用户或者说商业对手很容易猜测出来我们的一些敏感信息，比如商城在一天时间内，卖出了多少单，这明显不合适。</p>
<p>场景分析二：随着我们商城规模越来越大，mysql的单表的容量不宜超过500W，数据量过大之后，我们要进行拆库拆表，但拆分表了之后，他们从逻辑上讲他们是同一张表，所以他们的id是不能一样的， 于是乎我们需要保证id的唯一性。</p>
<p><strong>全局ID生成器</strong>，是一种在分布式系统下用来生成全局唯一ID的工具，一般要满足下列特性：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302047.png" srcset="/img/loading.gif" lazyload alt="1653363100502"></p>
<p>为了增加ID的安全性，我们可以不直接使用Redis自增的数值，而是拼接一些其它信息：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302048.png" srcset="/img/loading.gif" lazyload alt="1653363172079">ID的组成部分：符号位：1bit，永远为0</p>
<p>时间戳：31bit，以秒为单位，可以使用69年</p>
<p>序列号：32bit，秒内的计数器，支持每秒产生2^32个不同ID</p>
<h3 id="3-2-Redis实现全局唯一Id"><a href="#3-2-Redis实现全局唯一Id" class="headerlink" title="3.2 -Redis实现全局唯一Id"></a>3.2 -Redis实现全局唯一Id</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Component</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedisIdWorker</span> &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 开始时间戳</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">long</span> <span class="hljs-variable">BEGIN_TIMESTAMP</span> <span class="hljs-operator">=</span> <span class="hljs-number">1640995200L</span>;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 序列号的位数</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">COUNT_BITS</span> <span class="hljs-operator">=</span> <span class="hljs-number">32</span>;<br><br>    <span class="hljs-keyword">private</span> StringRedisTemplate stringRedisTemplate;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">RedisIdWorker</span><span class="hljs-params">(StringRedisTemplate stringRedisTemplate)</span> &#123;<br>        <span class="hljs-built_in">this</span>.stringRedisTemplate = stringRedisTemplate;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">long</span> <span class="hljs-title function_">nextId</span><span class="hljs-params">(String keyPrefix)</span> &#123;<br>        <span class="hljs-comment">// 1.生成时间戳</span><br>        <span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">now</span> <span class="hljs-operator">=</span> LocalDateTime.now();<br>        <span class="hljs-type">long</span> <span class="hljs-variable">nowSecond</span> <span class="hljs-operator">=</span> now.toEpochSecond(ZoneOffset.UTC);<br>        <span class="hljs-type">long</span> <span class="hljs-variable">timestamp</span> <span class="hljs-operator">=</span> nowSecond - BEGIN_TIMESTAMP;<br><br>        <span class="hljs-comment">// 2.生成序列号</span><br>        <span class="hljs-comment">// 2.1.获取当前日期，精确到天</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">date</span> <span class="hljs-operator">=</span> now.format(DateTimeFormatter.ofPattern(<span class="hljs-string">&quot;yyyy:MM:dd&quot;</span>));<br>        <span class="hljs-comment">// 2.2.自增长</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().increment(<span class="hljs-string">&quot;icr:&quot;</span> + keyPrefix + <span class="hljs-string">&quot;:&quot;</span> + date);<br><br>        <span class="hljs-comment">// 3.拼接并返回</span><br>        <span class="hljs-keyword">return</span> timestamp &lt;&lt; COUNT_BITS | count;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试类</p>
<p>知识小贴士：关于countdownlatch</p>
<p>countdownlatch名为信号枪：主要的作用是同步协调在多线程的等待于唤醒问题</p>
<p>我们如果没有CountDownLatch ，那么由于程序是异步的，当异步程序没有执行完时，主线程就已经执行完了，然后我们期望的是分线程全部走完之后，主线程再走，所以我们此时需要使用到CountDownLatch</p>
<p>CountDownLatch 中有两个最重要的方法</p>
<p>1、countDown</p>
<p>2、await</p>
<p>await 方法 是阻塞方法，我们担心分线程没有执行完时，main线程就先执行，所以使用await可以让main线程阻塞，那么什么时候main线程不再阻塞呢？当CountDownLatch  内部维护的 变量变为0时，就不再阻塞，直接放行，那么什么时候CountDownLatch   维护的变量变为0 呢，我们只需要调用一次countDown ，内部变量就减少1，我们让分线程和变量绑定， 执行完一个分线程就减少一个变量，当分线程全部走完，CountDownLatch 维护的变量就是0，此时await就不再阻塞，统计出来的时间也就是所有分线程执行完后的时间。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">void</span> <span class="hljs-title function_">testIdWorker</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException &#123;<br>    <span class="hljs-type">CountDownLatch</span> <span class="hljs-variable">latch</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CountDownLatch</span>(<span class="hljs-number">300</span>);<br><br>    <span class="hljs-type">Runnable</span> <span class="hljs-variable">task</span> <span class="hljs-operator">=</span> () -&gt; &#123;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>            <span class="hljs-type">long</span> <span class="hljs-variable">id</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>            System.out.println(<span class="hljs-string">&quot;id = &quot;</span> + id);<br>        &#125;<br>        latch.countDown();<br>    &#125;;<br>    <span class="hljs-type">long</span> <span class="hljs-variable">begin</span> <span class="hljs-operator">=</span> System.currentTimeMillis();<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">300</span>; i++) &#123;<br>        es.submit(task);<br>    &#125;<br>    latch.await();<br>    <span class="hljs-type">long</span> <span class="hljs-variable">end</span> <span class="hljs-operator">=</span> System.currentTimeMillis();<br>    System.out.println(<span class="hljs-string">&quot;time = &quot;</span> + (end - begin));<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-3-添加优惠卷"><a href="#3-3-添加优惠卷" class="headerlink" title="3.3 添加优惠卷"></a>3.3 添加优惠卷</h3><p>每个店铺都可以发布优惠券，分为平价券和特价券。平价券可以任意购买，而特价券需要秒杀抢购：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302049.png" srcset="/img/loading.gif" lazyload alt="1653365145124"></p>
<p>tb_voucher：优惠券的基本信息，优惠金额、使用规则等<br>tb_seckill_voucher：优惠券的库存、开始抢购时间，结束抢购时间。特价优惠券才需要填写这些信息</p>
<p>平价卷由于优惠力度并不是很大，所以是可以任意领取</p>
<p>而代金券由于优惠力度大，所以像第二种卷，就得限制数量，从表结构上也能看出，特价卷除了具有优惠卷的基本信息以外，还具有库存，抢购时间，结束时间等等字段</p>
<p>**新增普通卷代码：  **VoucherController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">addVoucher</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Voucher voucher)</span> &#123;<br>    voucherService.save(voucher);<br>    <span class="hljs-keyword">return</span> Result.ok(voucher.getId());<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>新增秒杀卷代码：</strong></p>
<p><strong>VoucherController</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;seckill&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">addSeckillVoucher</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Voucher voucher)</span> &#123;<br>    voucherService.addSeckillVoucher(voucher);<br>    <span class="hljs-keyword">return</span> Result.ok(voucher.getId());<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>VoucherServiceImpl</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-meta">@Transactional</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addSeckillVoucher</span><span class="hljs-params">(Voucher voucher)</span> &#123;<br>    <span class="hljs-comment">// 保存优惠券</span><br>    save(voucher);<br>    <span class="hljs-comment">// 保存秒杀信息</span><br>    <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">seckillVoucher</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SeckillVoucher</span>();<br>    seckillVoucher.setVoucherId(voucher.getId());<br>    seckillVoucher.setStock(voucher.getStock());<br>    seckillVoucher.setBeginTime(voucher.getBeginTime());<br>    seckillVoucher.setEndTime(voucher.getEndTime());<br>    seckillVoucherService.save(seckillVoucher);<br>    <span class="hljs-comment">// 保存秒杀库存到Redis中</span><br>    stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-4-实现秒杀下单"><a href="#3-4-实现秒杀下单" class="headerlink" title="3.4 实现秒杀下单"></a>3.4 实现秒杀下单</h3><p>下单核心思路：当我们点击抢购时，会触发右侧的请求，我们只需要编写对应的controller即可</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302050.png" srcset="/img/loading.gif" lazyload alt="1653365839526"></p>
<p>秒杀下单应该思考的内容：</p>
<p>下单时需要判断两点：</p>
<ul>
<li>秒杀是否开始或结束，如果尚未开始或已经结束则无法下单</li>
<li>库存是否充足，不足则无法下单</li>
</ul>
<p>下单核心逻辑分析：</p>
<p>当用户开始进行下单，我们应当去查询优惠卷信息，查询到优惠卷信息，判断是否满足秒杀条件</p>
<p>比如时间是否充足，如果时间充足，则进一步判断库存是否足够，如果两者都满足，则扣减库存，创建订单，然后返回订单id，如果有一个条件不满足则直接结束。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302051.png" srcset="/img/loading.gif" lazyload alt="1653366238564"></p>
<p>VoucherOrderServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>    <span class="hljs-comment">// 1.查询优惠券</span><br>    <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">voucher</span> <span class="hljs-operator">=</span> seckillVoucherService.getById(voucherId);<br>    <span class="hljs-comment">// 2.判断秒杀是否开始</span><br>    <span class="hljs-keyword">if</span> (voucher.getBeginTime().isAfter(LocalDateTime.now())) &#123;<br>        <span class="hljs-comment">// 尚未开始</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀尚未开始！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.判断秒杀是否已经结束</span><br>    <span class="hljs-keyword">if</span> (voucher.getEndTime().isBefore(LocalDateTime.now())) &#123;<br>        <span class="hljs-comment">// 尚未开始</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀已经结束！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 4.判断库存是否充足</span><br>    <span class="hljs-keyword">if</span> (voucher.getStock() &lt; <span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-comment">// 库存不足</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">//5，扣减库存</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>            .setSql(<span class="hljs-string">&quot;stock= stock -1&quot;</span>)<br>            .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).update();<br>    <span class="hljs-keyword">if</span> (!success) &#123;<br>        <span class="hljs-comment">//扣减库存</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">//6.创建订单</span><br>    <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>();<br>    <span class="hljs-comment">// 6.1.订单id</span><br>    <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>    voucherOrder.setId(orderId);<br>    <span class="hljs-comment">// 6.2.用户id</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    voucherOrder.setUserId(userId);<br>    <span class="hljs-comment">// 6.3.代金券id</span><br>    voucherOrder.setVoucherId(voucherId);<br>    save(voucherOrder);<br><br>    <span class="hljs-keyword">return</span> Result.ok(orderId);<br><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-5-库存超卖问题分析"><a href="#3-5-库存超卖问题分析" class="headerlink" title="3.5 库存超卖问题分析"></a>3.5 库存超卖问题分析</h3><p>有关超卖问题分析：在我们原有代码中是这么写的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">if</span> (voucher.getStock() &lt; <span class="hljs-number">1</span>) &#123;<br>       <span class="hljs-comment">// 库存不足</span><br>       <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>   &#125;<br>   <span class="hljs-comment">//5，扣减库存</span><br>   <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>           .setSql(<span class="hljs-string">&quot;stock= stock -1&quot;</span>)<br>           .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).update();<br>   <span class="hljs-keyword">if</span> (!success) &#123;<br>       <span class="hljs-comment">//扣减库存</span><br>       <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>

<p>假设线程1过来查询库存，判断出来库存大于1，正准备去扣减库存，但是还没有来得及去扣减，此时线程2过来，线程2也去查询库存，发现这个数量一定也大于1，那么这两个线程都会去扣减库存，最终多个线程相当于一起去扣减库存，此时就会出现库存的超卖问题。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302052.png" srcset="/img/loading.gif" lazyload alt="1653368335155"></p>
<p>超卖问题是典型的多线程安全问题，针对这一问题的常见解决方案就是加锁：而对于加锁，我们通常有两种解决方案：见下图：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302053.png" srcset="/img/loading.gif" lazyload alt="1653368562591"></p>
<p><strong>悲观锁：</strong></p>
<p> 悲观锁可以实现对于数据的串行化执行，比如syn，和lock都是悲观锁的代表，同时，悲观锁中又可以再细分为公平锁，非公平锁，可重入锁，等等</p>
<p><strong>乐观锁：</strong></p>
<p>  乐观锁：会有一个版本号，每次操作数据会对版本号+1，再提交回数据时，会去校验是否比之前的版本大1 ，如果大1 ，则进行操作成功，这套机制的核心逻辑在于，如果在操作过程中，版本号只比原来大1 ，那么就意味着操作过程中没有人对他进行过修改，他的操作就是安全的，如果不大1，则数据被修改过，当然乐观锁还有一些变种的处理方式比如cas</p>
<p>  乐观锁的典型代表：就是cas，利用cas进行无锁化机制加锁，var5 是操作前读取的内存值，while中的var1+var2 是预估值，如果预估值 &#x3D;&#x3D; 内存值，则代表中间没有被人修改过，此时就将新值去替换 内存值</p>
<p>  其中do while 是为了在操作失败时，再次进行自旋操作，即把之前的逻辑再操作一次。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">int</span> var5;<br><span class="hljs-keyword">do</span> &#123;<br>    var5 = <span class="hljs-built_in">this</span>.getIntVolatile(var1, var2);<br>&#125; <span class="hljs-keyword">while</span>(!<span class="hljs-built_in">this</span>.compareAndSwapInt(var1, var2, var5, var5 + var4));<br><br><span class="hljs-keyword">return</span> var5;<br></code></pre></td></tr></table></figure>

<p><strong>课程中的使用方式：</strong></p>
<p>课程中的使用方式是没有像cas一样带自旋的操作，也没有对version的版本号+1 ，他的操作逻辑是在操作时，对版本号进行+1 操作，然后要求version 如果是1 的情况下，才能操作，那么第一个线程在操作后，数据库中的version变成了2，但是他自己满足version&#x3D;1 ，所以没有问题，此时线程2执行，线程2 最后也需要加上条件version &#x3D;1 ，但是现在由于线程1已经操作过了，所以线程2，操作时就不满足version&#x3D;1 的条件了，所以线程2无法执行成功</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302054.png" srcset="/img/loading.gif" lazyload alt="1653369268550"></p>
<h3 id="3-6-乐观锁解决超卖问题"><a href="#3-6-乐观锁解决超卖问题" class="headerlink" title="3.6 乐观锁解决超卖问题"></a>3.6 乐观锁解决超卖问题</h3><p><strong>修改代码方案一、</strong></p>
<p>VoucherOrderServiceImpl 在扣减库存时，改为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>            .setSql(<span class="hljs-string">&quot;stock= stock -1&quot;</span>) <span class="hljs-comment">//set stock = stock -1</span><br>            .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).eq(<span class="hljs-string">&quot;stock&quot;</span>,voucher.getStock()).update(); <span class="hljs-comment">//where id = ？ and stock = ?</span><br></code></pre></td></tr></table></figure>

<p>以上逻辑的核心含义是：只要我扣减库存时的库存和之前我查询到的库存是一样的，就意味着没有人在中间修改过库存，那么此时就是安全的，但是以上这种方式通过测试发现会有很多失败的情况，失败的原因在于：在使用乐观锁过程中假设100个线程同时都拿到了100的库存，然后大家一起去进行扣减，但是100个人中只有1个人能扣减成功，其他的人在处理时，他们在扣减时，库存已经被修改过了，所以此时其他线程都会失败</p>
<p><strong>修改代码方案二、</strong></p>
<p>之前的方式要修改前后都保持一致，但是这样我们分析过，成功的概率太低，所以我们的乐观锁需要变一下，改成stock大于0 即可</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>            .setSql(<span class="hljs-string">&quot;stock= stock -1&quot;</span>)<br>            .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).update().gt(<span class="hljs-string">&quot;stock&quot;</span>,<span class="hljs-number">0</span>); <span class="hljs-comment">//where id = ? and stock &gt; 0</span><br></code></pre></td></tr></table></figure>

<p><strong>知识小扩展：</strong></p>
<p>针对cas中的自旋压力过大，我们可以使用Longaddr这个类去解决</p>
<p>Java8 提供的一个对AtomicLong改进后的一个类，LongAdder</p>
<p>大量线程并发更新一个原子性的时候，天然的问题就是自旋，会导致并发性问题，当然这也比我们直接使用syn来的好</p>
<p>所以利用这么一个类，LongAdder来进行优化</p>
<p>如果获取某个值，则会对cell和base的值进行递增，最后返回一个完整的值</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302055.png" srcset="/img/loading.gif" lazyload alt="1653370271627"></p>
<h3 id="3-6-优惠券秒杀-一人一单"><a href="#3-6-优惠券秒杀-一人一单" class="headerlink" title="3.6 优惠券秒杀-一人一单"></a>3.6 优惠券秒杀-一人一单</h3><p>需求：修改秒杀业务，要求同一个优惠券，一个用户只能下一单</p>
<p><strong>现在的问题在于：</strong></p>
<p>优惠卷是为了引流，但是目前的情况是，一个人可以无限制的抢这个优惠卷，所以我们应当增加一层逻辑，让一个用户只能下一个单，而不是让一个用户下多个单</p>
<p>具体操作逻辑如下：比如时间是否充足，如果时间充足，则进一步判断库存是否足够，然后再根据优惠卷id和用户id查询是否已经下过这个订单，如果下过这个订单，则不再下单，否则进行下单</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302056.png" srcset="/img/loading.gif" lazyload alt="1653371854389"></p>
<p>VoucherOrderServiceImpl  </p>
<p><strong>初步代码：增加一人一单逻辑</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>    <span class="hljs-comment">// 1.查询优惠券</span><br>    <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">voucher</span> <span class="hljs-operator">=</span> seckillVoucherService.getById(voucherId);<br>    <span class="hljs-comment">// 2.判断秒杀是否开始</span><br>    <span class="hljs-keyword">if</span> (voucher.getBeginTime().isAfter(LocalDateTime.now())) &#123;<br>        <span class="hljs-comment">// 尚未开始</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀尚未开始！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.判断秒杀是否已经结束</span><br>    <span class="hljs-keyword">if</span> (voucher.getEndTime().isBefore(LocalDateTime.now())) &#123;<br>        <span class="hljs-comment">// 尚未开始</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀已经结束！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 4.判断库存是否充足</span><br>    <span class="hljs-keyword">if</span> (voucher.getStock() &lt; <span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-comment">// 库存不足</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 5.一人一单逻辑</span><br>    <span class="hljs-comment">// 5.1.用户id</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-type">int</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).count();<br>    <span class="hljs-comment">// 5.2.判断是否存在</span><br>    <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">0</span>) &#123;<br>        <span class="hljs-comment">// 用户已经购买过了</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;用户已经购买过一次！&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-comment">//6，扣减库存</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>            .setSql(<span class="hljs-string">&quot;stock= stock -1&quot;</span>)<br>            .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).update();<br>    <span class="hljs-keyword">if</span> (!success) &#123;<br>        <span class="hljs-comment">//扣减库存</span><br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">//7.创建订单</span><br>    <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>();<br>    <span class="hljs-comment">// 7.1.订单id</span><br>    <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>    voucherOrder.setId(orderId);<br><br>    voucherOrder.setUserId(userId);<br>    <span class="hljs-comment">// 7.3.代金券id</span><br>    voucherOrder.setVoucherId(voucherId);<br>    save(voucherOrder);<br><br>    <span class="hljs-keyword">return</span> Result.ok(orderId);<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>存在问题：</strong>现在的问题还是和之前一样，并发过来，查询数据库，都不存在订单，所以我们还是需要加锁，但是乐观锁比较适合更新数据，而现在是插入数据，所以我们需要使用悲观锁操作</p>
<p><strong>注意：</strong>在这里提到了非常多的问题，我们需要慢慢的来思考，首先我们的初始方案是封装了一个createVoucherOrder方法，同时为了确保他线程安全，在方法上添加了一把synchronized 锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Transactional</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> Result <span class="hljs-title function_">createVoucherOrder</span><span class="hljs-params">(Long voucherId)</span> &#123;<br><br>	<span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>         <span class="hljs-comment">// 5.1.查询订单</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).count();<br>        <span class="hljs-comment">// 5.2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-comment">// 用户已经购买过了</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;用户已经购买过一次！&quot;</span>);<br>        &#125;<br><br>        <span class="hljs-comment">// 6.扣减库存</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>                .setSql(<span class="hljs-string">&quot;stock = stock - 1&quot;</span>) <span class="hljs-comment">// set stock = stock - 1</span><br>                .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).gt(<span class="hljs-string">&quot;stock&quot;</span>, <span class="hljs-number">0</span>) <span class="hljs-comment">// where id = ? and stock &gt; 0</span><br>                .update();<br>        <span class="hljs-keyword">if</span> (!success) &#123;<br>            <span class="hljs-comment">// 扣减失败</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>        &#125;<br><br>        <span class="hljs-comment">// 7.创建订单</span><br>        <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>();<br>        <span class="hljs-comment">// 7.1.订单id</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>        voucherOrder.setId(orderId);<br>        <span class="hljs-comment">// 7.2.用户id</span><br>        voucherOrder.setUserId(userId);<br>        <span class="hljs-comment">// 7.3.代金券id</span><br>        voucherOrder.setVoucherId(voucherId);<br>        save(voucherOrder);<br><br>        <span class="hljs-comment">// 7.返回订单id</span><br>        <span class="hljs-keyword">return</span> Result.ok(orderId);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>，但是这样添加锁，锁的粒度太粗了，在使用锁过程中，控制<strong>锁粒度</strong> 是一个非常重要的事情，因为如果锁的粒度太大，会导致每个线程进来都会锁住，所以我们需要去控制锁的粒度，以下这段代码需要修改为：<br>intern() 这个方法是从常量池中拿到数据，如果我们直接使用userId.toString() 他拿到的对象实际上是不同的对象，new出来的对象，我们使用锁必须保证锁必须是同一把，所以我们需要使用intern()方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Transactional</span><br><span class="hljs-keyword">public</span>  Result <span class="hljs-title function_">createVoucherOrder</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>	<span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>	<span class="hljs-keyword">synchronized</span>(userId.toString().intern())&#123;<br>         <span class="hljs-comment">// 5.1.查询订单</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).count();<br>        <span class="hljs-comment">// 5.2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-comment">// 用户已经购买过了</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;用户已经购买过一次！&quot;</span>);<br>        &#125;<br><br>        <span class="hljs-comment">// 6.扣减库存</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>                .setSql(<span class="hljs-string">&quot;stock = stock - 1&quot;</span>) <span class="hljs-comment">// set stock = stock - 1</span><br>                .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherId).gt(<span class="hljs-string">&quot;stock&quot;</span>, <span class="hljs-number">0</span>) <span class="hljs-comment">// where id = ? and stock &gt; 0</span><br>                .update();<br>        <span class="hljs-keyword">if</span> (!success) &#123;<br>            <span class="hljs-comment">// 扣减失败</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>        &#125;<br><br>        <span class="hljs-comment">// 7.创建订单</span><br>        <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>();<br>        <span class="hljs-comment">// 7.1.订单id</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>        voucherOrder.setId(orderId);<br>        <span class="hljs-comment">// 7.2.用户id</span><br>        voucherOrder.setUserId(userId);<br>        <span class="hljs-comment">// 7.3.代金券id</span><br>        voucherOrder.setVoucherId(voucherId);<br>        save(voucherOrder);<br><br>        <span class="hljs-comment">// 7.返回订单id</span><br>        <span class="hljs-keyword">return</span> Result.ok(orderId);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>但是以上代码还是存在问题，问题的原因在于当前方法被spring的事务控制，如果你在方法内部加锁，可能会导致当前方法事务还没有提交，但是锁已经释放也会导致问题，所以我们选择将当前方法整体包裹起来，确保事务不会出现问题：如下：</p>
<p>在seckillVoucher 方法中，添加以下逻辑，这样就能保证事务的特性，同时也控制了锁的粒度</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302057.png" srcset="/img/loading.gif" lazyload alt="1653373434815"></p>
<p>但是以上做法依然有问题，因为你调用的方法，其实是this.的方式调用的，事务想要生效，还得利用代理来生效，所以这个地方，我们需要获得原始的事务对象， 来操作事务</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302058.png" srcset="/img/loading.gif" lazyload alt="1653383810643"></p>
<h3 id="3-7-集群环境下的并发问题"><a href="#3-7-集群环境下的并发问题" class="headerlink" title="3.7 集群环境下的并发问题"></a>3.7 集群环境下的并发问题</h3><p>通过加锁可以解决在单机情况下的一人一单安全问题，但是在集群模式下就不行了。</p>
<p>1、我们将服务启动两份，端口分别为8081和8082：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302059.png" srcset="/img/loading.gif" lazyload alt="1653373887844"></p>
<p>2、然后修改nginx的conf目录下的nginx.conf文件，配置反向代理和负载均衡：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302060.png" srcset="/img/loading.gif" lazyload alt="1653373908620"></p>
<p><strong>具体操作(略)</strong></p>
<p><strong>有关锁失效原因分析</strong></p>
<p>由于现在我们部署了多个tomcat，每个tomcat都有一个属于自己的jvm，那么假设在服务器A的tomcat内部，有两个线程，这两个线程由于使用的是同一份代码，那么他们的锁对象是同一个，是可以实现互斥的，但是如果现在是服务器B的tomcat内部，又有两个线程，但是他们的锁对象写的虽然和服务器A一样，但是锁对象却不是同一个，所以线程3和线程4可以实现互斥，但是却无法和线程1和线程2实现互斥，这就是 集群环境下，syn锁失效的原因，在这种情况下，我们就需要使用分布式锁来解决这个问题。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302061.png" srcset="/img/loading.gif" lazyload alt="1653374044740"></p>
<h2 id="4、分布式锁"><a href="#4、分布式锁" class="headerlink" title="4、分布式锁"></a>4、分布式锁</h2><h3 id="4-1-、基本原理和实现方式对比"><a href="#4-1-、基本原理和实现方式对比" class="headerlink" title="4.1 、基本原理和实现方式对比"></a>4.1 、基本原理和实现方式对比</h3><p>分布式锁：满足分布式系统或集群模式下多进程可见并且互斥的锁。</p>
<p>分布式锁的核心思想就是让大家都使用同一把锁，只要大家使用的是同一把锁，那么我们就能锁住线程，不让线程进行，让程序串行执行，这就是分布式锁的核心思路</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302062.png" srcset="/img/loading.gif" lazyload alt="1653374296906"></p>
<p>那么分布式锁他应该满足一些什么样的条件呢？</p>
<p>可见性：多个线程都能看到相同的结果，注意：这个地方说的可见性并不是并发编程中指的内存可见性，只是说多个进程之间都能感知到变化的意思</p>
<p>互斥：互斥是分布式锁的最基本的条件，使得程序串行执行</p>
<p>高可用：程序不易崩溃，时时刻刻都保证较高的可用性</p>
<p>高性能：由于加锁本身就让性能降低，所有对于分布式锁本身就需要他较高的加锁性能和释放锁性能</p>
<p>安全性：安全也是程序中必不可少的一环</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302063.png" srcset="/img/loading.gif" lazyload alt="1653381992018"></p>
<p>常见的分布式锁有三种</p>
<p>Mysql：mysql本身就带有锁机制，但是由于mysql性能本身一般，所以使用mysql作为分布式锁比较少见。</p>
<p>Redis：redis作为分布式锁是非常常见的一种使用方式，现在企业级开发中基本都使用redis或者zookeeper作为分布式锁，利用setnx这个方法，如果插入key成功，则表示获得到了锁，如果有人插入成功，其他人插入失败则表示无法获得到锁，利用这套逻辑来实现分布式锁。</p>
<p>Zookeeper：zookeeper也是企业级开发中较好的一个实现分布式锁的方案。&#x2F;&#x2F; todo 待学习</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302064.png" srcset="/img/loading.gif" lazyload alt="1653382219377"></p>
<h3 id="4-2-、Redis分布式锁的实现核心思路"><a href="#4-2-、Redis分布式锁的实现核心思路" class="headerlink" title="4.2 、Redis分布式锁的实现核心思路"></a>4.2 、Redis分布式锁的实现核心思路</h3><p>实现分布式锁时需要实现的两个基本方法：</p>
<ul>
<li><p>获取锁：</p>
<ul>
<li>互斥：确保只能有一个线程获取锁</li>
<li>非阻塞：尝试一次，成功返回true，失败返回false</li>
</ul>
</li>
<li><p>释放锁：</p>
<ul>
<li><p>手动释放</p>
  <figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">Del Key<br></code></pre></td></tr></table></figure>
</li>
<li><p>超时释放：获取锁时添加一个超时时间</p>
</li>
</ul>
</li>
</ul>
<p>核心思路：</p>
<p>我们利用redis 的setnx 方法，当有多个线程进入时，我们就利用该方法，第一个线程进入时，redis 中就有这个key 了，返回了1，如果结果是1，则表示他抢到了锁，那么他去执行业务，然后再删除锁，退出锁逻辑，没有抢到锁的线程，等待一定时间后重试即可</p>
<p> <img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302066.png" srcset="/img/loading.gif" lazyload alt="1653382830810"></p>
<h3 id="4-3-实现分布式锁版本一"><a href="#4-3-实现分布式锁版本一" class="headerlink" title="4.3 实现分布式锁版本一"></a>4.3 实现分布式锁版本一</h3><ul>
<li>加锁逻辑</li>
</ul>
<p><strong>锁的基本接口</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">ILock</span> &#123;<br>    <span class="hljs-comment">/**尝试获取锁</span><br><span class="hljs-comment">	*<span class="hljs-doctag">@param</span> timeoutSec 锁持有的超时时间，过期后自动释放</span><br><span class="hljs-comment">	*<span class="hljs-doctag">@return</span> true代表获取锁成功; false代表获取锁失败</span><br><span class="hljs-comment">	*/</span><br>	<span class="hljs-type">boolean</span> <span class="hljs-title function_">tryLock</span><span class="hljs-params">(<span class="hljs-type">long</span> timeoutSec)</span>;<br>	<span class="hljs-comment">/**</span><br><span class="hljs-comment">	*释放锁</span><br><span class="hljs-comment">	*/</span><br>	<span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">()</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>SimpleRedisLock</strong></p>
<p>利用setnx方法进行加锁，同时增加过期时间，防止死锁，此方法<strong>可以保证加锁和增加过期时间具有原子性</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String KEY_PREFIX=<span class="hljs-string">&quot;lock:&quot;</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">tryLock</span><span class="hljs-params">(<span class="hljs-type">long</span> timeoutSec)</span> &#123;<br>    <span class="hljs-comment">// 获取线程标示</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">threadId</span> <span class="hljs-operator">=</span> Thread.currentThread().getId()<br>    <span class="hljs-comment">// 获取锁</span><br>    <span class="hljs-type">Boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue()<br>            .setIfAbsent(KEY_PREFIX + name, threadId + <span class="hljs-string">&quot;&quot;</span>, timeoutSec, TimeUnit.SECONDS);<br>    <span class="hljs-keyword">return</span> Boolean.TRUE.equals(success);<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>释放锁逻辑</li>
</ul>
<p>SimpleRedisLock</p>
<p>释放锁，防止删除别人的锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">//通过del删除锁</span><br>    stringRedisTemplate.delete(KEY_PREFIX + name);<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>修改业务代码</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br>  <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>      <span class="hljs-comment">// 1.查询优惠券</span><br>      <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">voucher</span> <span class="hljs-operator">=</span> seckillVoucherService.getById(voucherId);<br>      <span class="hljs-comment">// 2.判断秒杀是否开始</span><br>      <span class="hljs-keyword">if</span> (voucher.getBeginTime().isAfter(LocalDateTime.now())) &#123;<br>          <span class="hljs-comment">// 尚未开始</span><br>          <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀尚未开始！&quot;</span>);<br>      &#125;<br>      <span class="hljs-comment">// 3.判断秒杀是否已经结束</span><br>      <span class="hljs-keyword">if</span> (voucher.getEndTime().isBefore(LocalDateTime.now())) &#123;<br>          <span class="hljs-comment">// 尚未开始</span><br>          <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀已经结束！&quot;</span>);<br>      &#125;<br>      <span class="hljs-comment">// 4.判断库存是否充足</span><br>      <span class="hljs-keyword">if</span> (voucher.getStock() &lt; <span class="hljs-number">1</span>) &#123;<br>          <span class="hljs-comment">// 库存不足</span><br>          <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>      &#125;<br>      <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>      <span class="hljs-comment">//创建锁对象(新增代码)</span><br>      <span class="hljs-type">SimpleRedisLock</span> <span class="hljs-variable">lock</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleRedisLock</span>(<span class="hljs-string">&quot;order:&quot;</span> + userId, stringRedisTemplate);<br>      <span class="hljs-comment">//获取锁对象</span><br>      <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> lock.tryLock(<span class="hljs-number">1200</span>);<br><span class="hljs-comment">//加锁失败</span><br>      <span class="hljs-keyword">if</span> (!isLock) &#123;<br>          <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;不允许重复下单&quot;</span>);<br>      &#125;<br>      <span class="hljs-keyword">try</span> &#123;<br>          <span class="hljs-comment">//获取代理对象(事务)</span><br>          <span class="hljs-type">IVoucherOrderService</span> <span class="hljs-variable">proxy</span> <span class="hljs-operator">=</span> (IVoucherOrderService) AopContext.currentProxy();<br>          <span class="hljs-keyword">return</span> proxy.createVoucherOrder(voucherId);<br>      &#125; <span class="hljs-keyword">finally</span> &#123;<br>          <span class="hljs-comment">//释放锁</span><br>          lock.unlock();<br>      &#125;<br>  &#125;<br></code></pre></td></tr></table></figure>

<h3 id="4-4-Redis分布式锁误删情况说明"><a href="#4-4-Redis分布式锁误删情况说明" class="headerlink" title="4.4 Redis分布式锁误删情况说明"></a>4.4 Redis分布式锁误删情况说明</h3><p><strong>逻辑说明</strong>：</p>
<p>持有锁的线程1在锁的内部出现了阻塞，导致锁自动释放，这时线程2来尝试获得锁，就拿到了这把锁，然后线程2在持有锁执行过程中，线程1反应过来，继续执行，而线程1执行过程中，走到了删除锁逻辑，此时就会把本应该属于线程2的锁进行删除，这就是锁误删。</p>
<p><strong>解决方案</strong>：</p>
<p>在每个线程释放锁的时候，去判断一下当前这把锁是否属于自己，如果不属于自己，则不进行锁的删除。</p>
<p>假设还是上边的情况，线程1卡顿，锁自动释放，线程2进入到锁的内部执行逻辑，此时线程1反应过来，然后删除锁，但是线程1发现锁不属于自己，于是不进行删除锁逻辑，当线程2走到删除锁逻辑时，如果没有卡过自动释放锁的时间点，则判断当前这把锁是属于自己的，于是删除这把锁。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302069.png" srcset="/img/loading.gif" lazyload alt="1653385920025"></p>
<h3 id="4-5-解决Redis分布式锁误删问题"><a href="#4-5-解决Redis分布式锁误删问题" class="headerlink" title="4.5 解决Redis分布式锁误删问题"></a>4.5 解决Redis分布式锁误删问题</h3><p>需求：修改之前的分布式锁实现，满足：在获取锁时存入线程标示（可以用UUID表示）<br>在释放锁时先获取锁中的线程标示，判断是否与当前线程标示一致</p>
<ul>
<li>如果一致则释放锁</li>
<li>如果不一致则不释放锁</li>
</ul>
<p>核心逻辑：在存入锁时，放入自己线程的标识，在删除锁时，判断当前这把锁的标识是不是自己存入的，如果是，则进行删除，如果不是，则不进行删除。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302070.png" srcset="/img/loading.gif" lazyload alt="1653387398820"></p>
<p>具体代码如下：</p>
<p>加锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">ID_PREFIX</span> <span class="hljs-operator">=</span> UUID.randomUUID().toString(<span class="hljs-literal">true</span>) + <span class="hljs-string">&quot;-&quot;</span>;<br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">tryLock</span><span class="hljs-params">(<span class="hljs-type">long</span> timeoutSec)</span> &#123;<br>   <span class="hljs-comment">// 获取线程标示</span><br>   <span class="hljs-type">String</span> <span class="hljs-variable">threadId</span> <span class="hljs-operator">=</span> ID_PREFIX + Thread.currentThread().getId();<br>   <span class="hljs-comment">// 获取锁</span><br>   <span class="hljs-type">Boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue()<br>                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);<br>   <span class="hljs-keyword">return</span> Boolean.TRUE.equals(success);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>释放锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 获取线程标示</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">threadId</span> <span class="hljs-operator">=</span> ID_PREFIX + Thread.currentThread().getId();<br>    <span class="hljs-comment">// 获取锁中的标示</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">id</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);<br>    <span class="hljs-comment">// 判断标示是否一致</span><br>    <span class="hljs-keyword">if</span>(threadId.equals(id)) &#123;<br>        <span class="hljs-comment">// 释放锁</span><br>        stringRedisTemplate.delete(KEY_PREFIX + name);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>有关代码实操说明：</strong></p>
<p>启动两个线程，第一个线程持有锁后手动释放锁，第二个线程此时进入到锁内部，再放行第一个线程，此时第一个线程由于锁的value值并非是自己，所以不能释放锁，也就无法删除别人的锁，此时第二个线程能够正确释放锁。</p>
<h3 id="4-6-分布式锁的原子性问题"><a href="#4-6-分布式锁的原子性问题" class="headerlink" title="4.6 分布式锁的原子性问题"></a>4.6 分布式锁的原子性问题</h3><p>更为极端的误删逻辑说明：条件判断与锁删除操作的原子性</p>
<p>已经拿到了当前这把锁确实是属于他自己的，正准备删除锁，但是此时他的锁到期了，那么此时线程2进来，但是线程1他会接着往后执行，当他卡顿结束后，他直接就会执行删除锁那行代码，<strong>相当于条件判断并没有起到作用</strong>，这就是删锁时的原子性问题，之所以有这个问题，是因为线程1的<strong>拿锁，比锁，删锁，实际上并不是原子性的</strong>，我们要防止刚才的情况发生，</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302071.png" srcset="/img/loading.gif" lazyload alt="1653387764938"></p>
<h3 id="4-7-Lua脚本解决多条命令原子性问题"><a href="#4-7-Lua脚本解决多条命令原子性问题" class="headerlink" title="4.7 Lua脚本解决多条命令原子性问题"></a>4.7 Lua脚本解决多条命令原子性问题</h3><p>Redis提供了Lua脚本功能，在一个脚本中编写多条Redis命令，确保多条命令执行时的原子性。Lua是一种编程语言，基本语法参考网站：<a target="_blank" rel="noopener" href="https://www.runoob.com/lua/lua-tutorial.html%EF%BC%8C%E8%BF%99%E9%87%8C%E9%87%8D%E7%82%B9%E4%BB%8B%E7%BB%8DRedis%E6%8F%90%E4%BE%9B%E7%9A%84%E8%B0%83%E7%94%A8%E5%87%BD%E6%95%B0%EF%BC%8C%E6%88%91%E4%BB%AC%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8lua%E5%8E%BB%E6%93%8D%E4%BD%9Credis%EF%BC%8C%E5%8F%88%E8%83%BD%E4%BF%9D%E8%AF%81%E4%BB%96%E7%9A%84%E5%8E%9F%E5%AD%90%E6%80%A7%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%AE%9E%E7%8E%B0%E6%8B%BF%E9%94%81%E6%AF%94%E9%94%81%E5%88%A0%E9%94%81%E6%98%AF%E4%B8%80%E4%B8%AA%E5%8E%9F%E5%AD%90%E6%80%A7%E5%8A%A8%E4%BD%9C%E4%BA%86%E3%80%82">https://www.runoob.com/lua/lua-tutorial.html，这里重点介绍Redis提供的调用函数，我们可以使用lua去操作redis，又能保证他的原子性，这样就可以实现拿锁比锁删锁是一个原子性动作了。</a></p>
<p>这里重点介绍Redis提供的调用函数，语法如下：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs lua">redis.call(<span class="hljs-string">&#x27;命令名称&#x27;</span>, <span class="hljs-string">&#x27;key&#x27;</span>, <span class="hljs-string">&#x27;其它参数&#x27;</span>, ...)<br></code></pre></td></tr></table></figure>

<p>例如，我们要执行set name jack，则脚本是这样：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs lua"># 执行 set name jack<br>redis.call(<span class="hljs-string">&#x27;set&#x27;</span>, <span class="hljs-string">&#x27;name&#x27;</span>, <span class="hljs-string">&#x27;jack&#x27;</span>)<br></code></pre></td></tr></table></figure>

<p>例如，我们要先执行set name Rose，再执行get name，则脚本如下：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs lua"># 先执行 set name jack<br>redis.call(<span class="hljs-string">&#x27;set&#x27;</span>, <span class="hljs-string">&#x27;name&#x27;</span>, <span class="hljs-string">&#x27;Rose&#x27;</span>)<br># 再执行 get name<br><span class="hljs-keyword">local</span> name = redis.call(<span class="hljs-string">&#x27;get&#x27;</span>, <span class="hljs-string">&#x27;name&#x27;</span>)<br># 返回<br><span class="hljs-keyword">return</span> name<br></code></pre></td></tr></table></figure>

<p>写好脚本以后，需要用Redis命令来调用脚本，调用脚本的常见命令如下：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302072.png" srcset="/img/loading.gif" lazyload alt="1653392181413"></p>
<p>例如，我们要执行 redis.call(‘set’, ‘name’, ‘jack’) 这个脚本，语法如下：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302073.png" srcset="/img/loading.gif" lazyload alt="1653392218531"></p>
<p>如果脚本中的key、value不想写死，可以作为参数传递。key类型参数会放入KEYS数组，其它参数会放入ARGV数组，在脚本中可以从KEYS和ARGV数组获取这些参数：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302074.png" srcset="/img/loading.gif" lazyload alt="1653392438917"></p>
<p>释放锁的业务流程是这样的</p>
<p>​	1、获取锁中的线程标示</p>
<p>​	2、判断是否与指定的标示（当前线程标示）一致</p>
<p>​	3、如果一致则释放锁（删除）</p>
<p>​	4、如果不一致则什么都不做</p>
<p>如果用Lua脚本来表示则是这样的：</p>
<p>最终我们操作redis的拿锁比锁删锁的lua脚本就会变成这样</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-comment">-- 这里的 KEYS[1] 就是锁的key，这里的ARGV[1] 就是当前线程标示</span><br><span class="hljs-comment">-- 获取锁中的标示，判断是否与当前线程标示一致</span><br><span class="hljs-keyword">if</span> (redis.call(<span class="hljs-string">&#x27;GET&#x27;</span>, KEYS[<span class="hljs-number">1</span>]) == ARGV[<span class="hljs-number">1</span>]) <span class="hljs-keyword">then</span><br>  <span class="hljs-comment">-- 一致，则删除锁</span><br>  <span class="hljs-keyword">return</span> redis.call(<span class="hljs-string">&#x27;DEL&#x27;</span>, KEYS[<span class="hljs-number">1</span>])<br><span class="hljs-keyword">end</span><br><span class="hljs-comment">-- 不一致，则直接返回</span><br><span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br></code></pre></td></tr></table></figure>



<h3 id="4-8-利用Java代码调用Lua脚本改造分布式锁"><a href="#4-8-利用Java代码调用Lua脚本改造分布式锁" class="headerlink" title="4.8 利用Java代码调用Lua脚本改造分布式锁"></a>4.8 利用Java代码调用Lua脚本改造分布式锁</h3><p>lua脚本本身并不需要大家花费太多时间去研究，只需要知道如何调用，大致是什么意思即可，所以在笔记中并不会详细的去解释这些lua表达式的含义。</p>
<p>我们的RedisTemplate中，可以利用execute方法去执行lua脚本，参数对应关系就如下图股</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302075.png" srcset="/img/loading.gif" lazyload alt="1653393304844"></p>
<p><strong>Java代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 利用静态变量与静态代码块初始化</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> DefaultRedisScript&lt;Long&gt; UNLOCK_SCRIPT;<br>    <span class="hljs-keyword">static</span> &#123;<br>        UNLOCK_SCRIPT = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DefaultRedisScript</span>&lt;&gt;();<br>        <span class="hljs-comment">// 设置脚本地址</span><br>        UNLOCK_SCRIPT.setLocation(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ClassPathResource</span>(<span class="hljs-string">&quot;unlock.lua&quot;</span>));<br>        <span class="hljs-comment">// 设置返回类型</span><br>        UNLOCK_SCRIPT.setResultType(Long.class);<br>    &#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">unlock</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 调用lua脚本</span><br>    stringRedisTemplate.execute(<br>            UNLOCK_SCRIPT,<br>            Collections.singletonList(KEY_PREFIX + name),<br>            ID_PREFIX + Thread.currentThread().getId());<br>&#125;<br><span class="hljs-comment">// 经过以上代码改造后，我们就能够实现 拿锁比锁删锁的原子性动作了~</span><br></code></pre></td></tr></table></figure>

<p>小总结：</p>
<p>基于Redis的分布式锁实现思路：</p>
<ul>
<li>利用set nx ex获取锁，并设置过期时间，保存线程标示</li>
<li>释放锁时先判断线程标示是否与自己一致，一致则删除锁<ul>
<li>特性：<ul>
<li>利用set nx满足互斥性</li>
<li>利用set ex保证故障时锁依然能释放，避免死锁，提高安全性</li>
<li>利用Redis集群保证高可用和高并发特性</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>笔者总结：我们一路走来，利用添加过期时间，防止死锁问题的发生，但是有了过期时间之后，可能出现误删别人锁的问题，这个问题我们开始是利用删之前通过拿锁，比锁，删锁这个逻辑来解决的，也就是删之前判断一下当前这把锁是否是属于自己的，但是现在还有原子性问题，也就是我们没法保证拿锁比锁删锁是一个原子性的动作，最后通过lua表达式来解决这个问题</p>
<p>但是目前还剩下一个问题锁不住，什么是锁不住呢，你想一想，如果当过期时间到了之后，我们可以给他续期一下，比如续个30s，就好像是网吧上网， 网费到了之后，然后说，来，网管，再给我来10块的，是不是后边的问题都不会发生了，那么续期问题怎么解决呢，可以依赖于我们接下来要学习redission啦</p>
<p><strong>测试逻辑：</strong></p>
<p>第一个线程进来，得到了锁，手动删除锁，模拟锁超时了，其他线程会执行lua来抢锁，当第一个线程利用lua删除锁时，lua能保证他不能删锁，第二个线程删除锁时，利用lua同样可以保证不会删除别人的锁，同时还能保证原子性。</p>
<h2 id="5、分布式锁-redission"><a href="#5、分布式锁-redission" class="headerlink" title="5、分布式锁-redission"></a>5、分布式锁-redission</h2><h3 id="5-1-分布式锁-redission功能介绍"><a href="#5-1-分布式锁-redission功能介绍" class="headerlink" title="5.1 分布式锁-redission功能介绍"></a>5.1 分布式锁-redission功能介绍</h3><p>基于setnx实现的分布式锁存在下面的问题：</p>
<p><strong>重入问题</strong>：重入问题是指 获得锁的线程可以再次进入到相同的锁的代码块中，可重入锁的意义在于防止死锁，比如HashTable这样的代码中，他的方法都是使用synchronized修饰的，假如他在一个方法内，调用另一个方法，那么此时如果是不可重入的，不就死锁了吗？所以<strong>可重入锁的主要意义是防止死锁</strong>，我们的<strong>synchronized和Lock锁都是可重入的</strong>。</p>
<p><strong>不可重试</strong>：是指目前的分布式只能尝试一次，我们认为合理的情况是：当线程在获得锁失败后，他应该能再次尝试获得锁。</p>
<p><strong>超时释放：</strong>我们在加锁时增加了过期时间，这样的我们可以防止死锁，但是如果卡顿的时间超长，虽然我们采用了lua表达式防止删锁的时候误删别人的锁，但是毕竟没有锁住，有安全隐患</p>
<p><strong>主从一致性：</strong> 如果Redis提供了主从集群，当我们向集群写数据时，主机需要异步的将数据同步给从机，而万一在同步过去之前，主机宕机了，就会出现死锁问题。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302076.png" srcset="/img/loading.gif" lazyload alt="1653546070602"></p>
<p>那么什么是Redission呢</p>
<p>Redisson是一个在Redis的基础上实现的Java驻内存数据网格（In-Memory Data Grid）。它不仅提供了一系列的分布式的Java常用对象，还<strong>提供了许多分布式服务</strong>，其中就包含了<strong>各种分布式锁的实现</strong>（其实就是一个分布式工具包）。</p>
<p>Redission提供了分布式锁的多种多样的功能</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302077.png" srcset="/img/loading.gif" lazyload alt="1653546736063"></p>
<h3 id="5-2-分布式锁-Redission快速入门"><a href="#5-2-分布式锁-Redission快速入门" class="headerlink" title="5.2 分布式锁-Redission快速入门"></a>5.2 分布式锁-Redission快速入门</h3><p>引入依赖：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;dependency&gt;<br>	&lt;groupId&gt;org.redisson&lt;/groupId&gt;<br>	&lt;artifactId&gt;redisson&lt;/artifactId&gt;<br>	&lt;version&gt;<span class="hljs-number">3.13</span><span class="hljs-number">.6</span>&lt;/version&gt;<br>&lt;/dependency&gt;<br></code></pre></td></tr></table></figure>

<p>配置Redisson客户端：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedissonConfig</span> &#123;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> RedissonClient <span class="hljs-title function_">redissonClient</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-comment">// 配置</span><br>        <span class="hljs-type">Config</span> <span class="hljs-variable">config</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Config</span>();<br>        config.useSingleServer()	<span class="hljs-comment">// Redis为单节点</span><br>            .setAddress(<span class="hljs-string">&quot;redis://192.168.150.101:6379&quot;</span>)<br>            .setPassword(<span class="hljs-string">&quot;123321&quot;</span>);<br>        <span class="hljs-comment">// 创建RedissonClient对象</span><br>        <span class="hljs-keyword">return</span> Redisson.create(config);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>如何使用Redission的分布式锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Resource</span><br><span class="hljs-keyword">private</span> RedissionClient redissonClient;<br><br><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">void</span> <span class="hljs-title function_">testRedisson</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception&#123;<br>    <span class="hljs-comment">// 获取锁(可重入)，指定锁的名称</span><br>    <span class="hljs-type">RLock</span> <span class="hljs-variable">lock</span> <span class="hljs-operator">=</span> redissonClient.getLock(<span class="hljs-string">&quot;anyLock&quot;</span>);<br>    <span class="hljs-comment">// 尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位</span><br>    <span class="hljs-comment">// 锁自动释放时间不传参默认为30s</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> lock.tryLock(<span class="hljs-number">1</span>,<span class="hljs-number">10</span>,TimeUnit.SECONDS);<br>    <span class="hljs-comment">// 判断获取锁成功</span><br>    <span class="hljs-keyword">if</span>(isLock)&#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>            System.out.println(<span class="hljs-string">&quot;执行业务&quot;</span>);          <br>        &#125;<span class="hljs-keyword">finally</span>&#123;<br>            <span class="hljs-comment">//释放锁</span><br>            lock.unlock();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在 VoucherOrderServiceImpl</p>
<p>注入RedissonClient</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Resource</span><br><span class="hljs-keyword">private</span> RedissonClient redissonClient;<br><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>        <span class="hljs-comment">// 1.查询优惠券</span><br>        <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">voucher</span> <span class="hljs-operator">=</span> seckillVoucherService.getById(voucherId);<br>        <span class="hljs-comment">// 2.判断秒杀是否开始</span><br>        <span class="hljs-keyword">if</span> (voucher.getBeginTime().isAfter(LocalDateTime.now())) &#123;<br>            <span class="hljs-comment">// 尚未开始</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀尚未开始！&quot;</span>);<br>        &#125;<br>        <span class="hljs-comment">// 3.判断秒杀是否已经结束</span><br>        <span class="hljs-keyword">if</span> (voucher.getEndTime().isBefore(LocalDateTime.now())) &#123;<br>            <span class="hljs-comment">// 尚未开始</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;秒杀已经结束！&quot;</span>);<br>        &#125;<br>        <span class="hljs-comment">// 4.判断库存是否充足</span><br>        <span class="hljs-keyword">if</span> (voucher.getStock() &lt; <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-comment">// 库存不足</span><br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;库存不足！&quot;</span>);<br>        &#125;<br>        <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>        <span class="hljs-comment">// 创建锁对象 这个代码不用了，因为我们现在要使用分布式锁</span><br>        <span class="hljs-comment">// SimpleRedisLock lock = new SimpleRedisLock(&quot;order:&quot; + userId, stringRedisTemplate);</span><br>    	<span class="hljs-comment">// 获取锁对象</span><br>        <span class="hljs-type">RLock</span> <span class="hljs-variable">lock</span> <span class="hljs-operator">=</span> redissonClient.getLock(<span class="hljs-string">&quot;lock:order:&quot;</span> + userId);<br>        <span class="hljs-comment">// 尝试加锁</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> lock.tryLock();<br>       <br>		<span class="hljs-comment">// 加锁失败</span><br>        <span class="hljs-keyword">if</span> (!isLock) &#123;<br>            <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;不允许重复下单&quot;</span>);<br>        &#125;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 获取代理对象(事务)</span><br>            <span class="hljs-comment">// 使用代理对象才可以使事务生效</span><br>            <span class="hljs-type">IVoucherOrderService</span> <span class="hljs-variable">proxy</span> <span class="hljs-operator">=</span> (IVoucherOrderService) AopContext.currentProxy();<br>            <span class="hljs-keyword">return</span> proxy.createVoucherOrder(voucherId);<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-comment">// 释放锁</span><br>            lock.unlock();<br>        &#125;<br> &#125;<br></code></pre></td></tr></table></figure>

<h3 id="5-3-分布式锁-redission可重入锁原理"><a href="#5-3-分布式锁-redission可重入锁原理" class="headerlink" title="5.3 分布式锁-redission可重入锁原理"></a>5.3 分布式锁-redission可重入锁原理</h3><p>在Lock锁中，他是借助于底层的一个voaltile的一个state变量来记录重入的状态的，比如当前没有人持有这把锁，那么state&#x3D;0，假如有人持有这把锁，那么state&#x3D;1，如果持有这把锁的人再次持有这把锁，那么state就会+1 ，如果是对于synchronized而言，他在c语言代码中会有一个count，原理和state类似，也是重入一次就加一，释放一次就-1 ，直到减少成0 时，表示当前这把锁没有被人持有。  </p>
<p>在redission中也支持可重入锁</p>
<p>在分布式锁中，他采用hash结构用来存储锁，其中大key表示这把锁是否存在，用小key表示当前这把锁被哪个线程持有，所以接下来我们一起分析一下当前的这个lua表达式</p>
<p>这个地方一共有3个参数</p>
<p><strong>KEYS[1] ： 锁名称</strong></p>
<p><strong>ARGV[1]：  锁失效时间</strong></p>
<p><strong>ARGV[2]：  id + “:” + threadId; 锁的小key</strong></p>
<p>exists: 判断数据是否存在，如果&#x3D;&#x3D;0，就表示当前这把锁不存在，此时他就开始往redis里边去写数据 ，写成一个hash结构</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-keyword">if</span> (redis.call(<span class="hljs-string">&#x27;exists&#x27;</span>, KEYS[<span class="hljs-number">1</span>]) == <span class="hljs-number">0</span>) <span class="hljs-keyword">then</span><br>	redis.call(<span class="hljs-string">&#x27;hset&#x27;</span>, KEYS[<span class="hljs-number">1</span>], ARGV[<span class="hljs-number">2</span>], <span class="hljs-number">1</span>);<br>    redis.call(<span class="hljs-string">&#x27;pexpire&#x27;</span>, KEYS[<span class="hljs-number">1</span>], ARGV[<span class="hljs-number">1</span>]);<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>;<br><span class="hljs-keyword">end</span>;<br></code></pre></td></tr></table></figure>

<figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ada">Lock&#123;<br>	id + <span class="hljs-string">&quot;:&quot;</span> + threadId :  1<br>&#125;<br></code></pre></td></tr></table></figure>

<p>如果当前这把锁存在，则第一个条件不满足，再判断</p>
<p>此时需要通过大key+小key判断当前这把锁是否是属于自己的，如果是自己的，则进行</p>
<ul>
<li>将当前这个锁的value进行+1 </li>
<li>对其设置过期时间</li>
</ul>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-keyword">if</span> (redis.call(<span class="hljs-string">&#x27;hexists&#x27;</span>, KEYS[<span class="hljs-number">1</span>], ARGV[<span class="hljs-number">2</span>]) == <span class="hljs-number">1</span>) <span class="hljs-keyword">then</span><br>    redis.call(<span class="hljs-string">&#x27;hincrby&#x27;</span>, KEYS[<span class="hljs-number">1</span>], ARGV[<span class="hljs-number">2</span>], <span class="hljs-number">1</span>);<br>    redis.call(<span class="hljs-string">&#x27;pexpire&#x27;</span>, KEYS[<span class="hljs-number">1</span>], ARGV[<span class="hljs-number">1</span>]);<br><span class="hljs-keyword">end</span>; <br></code></pre></td></tr></table></figure>

<p>如果以上两个条件都不满足，则表示当前这把锁抢锁失败，最后返回pttl，即为当前这把锁的失效时间.</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-keyword">return</span> redis.call(<span class="hljs-string">&#x27;pttl&#x27;</span>, KEYS[<span class="hljs-number">1</span>]);<br></code></pre></td></tr></table></figure>

<p>如果小伙帮们看了前边的源码， 你会发现他会去判断当前这个方法的返回值是否为null，如果是null，则对应则前两个if对应的条件，退出抢锁逻辑，如果返回的不是null，即走了第三个分支，在源码处会进行while(true)的自旋抢锁。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-string">&quot;if (redis.call(&#x27;exists&#x27;, KEYS[1]) == 0) then &quot;</span> +<br>    <span class="hljs-string">&quot;redis.call(&#x27;hset&#x27;, KEYS[1], ARGV[2], 1); &quot;</span> +<br>    <span class="hljs-string">&quot;redis.call(&#x27;pexpire&#x27;, KEYS[1], ARGV[1]); &quot;</span> +<br>    <span class="hljs-string">&quot;return nil; &quot;</span> +<br><span class="hljs-string">&quot;end; &quot;</span> +<br><span class="hljs-string">&quot;if (redis.call(&#x27;hexists&#x27;, KEYS[1], ARGV[2]) == 1) then &quot;</span> +<br>    <span class="hljs-string">&quot;redis.call(&#x27;hincrby&#x27;, KEYS[1], ARGV[2], 1); &quot;</span> +<br>    <span class="hljs-string">&quot;redis.call(&#x27;pexpire&#x27;, KEYS[1], ARGV[1]); &quot;</span> +<br>    <span class="hljs-string">&quot;return nil; &quot;</span> +<br><span class="hljs-string">&quot;end; &quot;</span> +<br><span class="hljs-string">&quot;return redis.call(&#x27;pttl&#x27;, KEYS[1]);&quot;</span><br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302078.png" srcset="/img/loading.gif" lazyload alt="1653548087334"></p>
<h3 id="5-4-分布式锁-redission锁重试和WatchDog机制"><a href="#5-4-分布式锁-redission锁重试和WatchDog机制" class="headerlink" title="5.4 分布式锁-redission锁重试和WatchDog机制"></a>5.4 分布式锁-redission锁重试和WatchDog机制</h3><p><strong>说明</strong>：由于课程中已经说明了有关tryLock的源码解析以及其看门狗原理，所以笔者在这里给大家分析lock()方法的源码解析，希望大家在学习过程中，能够掌握更多的知识</p>
<p>抢锁过程中，获得当前线程，通过tryAcquire进行抢锁，该抢锁逻辑和之前逻辑相同</p>
<p>1、先判断当前这把锁是否存在，如果不存在，插入一把锁，返回null</p>
<p>2、判断当前这把锁是否是属于当前线程，如果是，则返回null</p>
<p>所以如果返回是null，则代表着当前这哥们已经抢锁完毕，或者可重入完毕，但是如果以上两个条件都不满足，则进入到第三个条件，返回的是锁的失效时间，同学们可以自行往下翻一点点，你能发现有个while( true) 再次进行tryAcquire进行抢锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">long</span> <span class="hljs-variable">threadId</span> <span class="hljs-operator">=</span> Thread.currentThread().getId();<br><span class="hljs-type">Long</span> <span class="hljs-variable">ttl</span> <span class="hljs-operator">=</span> tryAcquire(-<span class="hljs-number">1</span>, leaseTime, unit, threadId);<br><span class="hljs-comment">// lock acquired</span><br><span class="hljs-keyword">if</span> (ttl == <span class="hljs-literal">null</span>) &#123;<br>    <span class="hljs-keyword">return</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>接下来会有一个条件分支，因为lock方法有重载方法，一个是带参数，一个是不带参数，如果不带参数传入的值是-1，如果传入参数，则leaseTime是他本身，所以如果传入了参数，此时leaseTime !&#x3D; -1 则会进去抢锁，抢锁的逻辑就是之前说的那三个逻辑</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">if</span> (leaseTime != -<span class="hljs-number">1</span>) &#123;<br>    <span class="hljs-keyword">return</span> tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_LONG);<br>&#125;<br></code></pre></td></tr></table></figure>



<p>如果是没有传入时间，则此时也会进行抢锁， 而且抢锁时间是默认看门狗时间 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout()<br></code></pre></td></tr></table></figure>



<p>对以上抢锁进行了监听，当上边抢锁完毕后，此方法会被调用，具体调用的逻辑就是去后台开启一个线程，进行续约逻辑，也就是看门狗线程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">ttlRemainingFuture.onComplete((ttlRemaining, e) <br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java">RFuture&lt;Long&gt; ttlRemainingFuture = tryLockInnerAsync(<br>        waitTime,<br>        commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(),<br>        TimeUnit.MILLISECONDS, <br>        threadId, <br>        RedisCommands.EVAL_LONG);<br>ttlRemainingFuture.onComplete((ttlRemaining, e) -&gt; &#123;<br>    <span class="hljs-keyword">if</span> (e != <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-keyword">return</span>;<br>    &#125;<br>    <span class="hljs-comment">// lock acquired</span><br>    <span class="hljs-keyword">if</span> (ttlRemaining == <span class="hljs-literal">null</span>) &#123;<br>        scheduleExpirationRenewal(threadId);<br>    &#125;<br>&#125;);<br><span class="hljs-keyword">return</span> ttlRemainingFuture;<br></code></pre></td></tr></table></figure>



<p>此逻辑就是续约逻辑，注意看commandExecutor.getConnectionManager().newTimeout（） 此方法</p>
<p>Method(  <strong>new</strong> TimerTask() {},参数2 ，参数3  )</p>
<p>指的是：通过参数2，参数3 去描述什么时候去做参数1的事情，现在的情况是：10s之后去做参数一的事情</p>
<p>因为锁的失效时间是30s，当10s之后，此时这个timeTask 就触发了，他就去进行续约，把当前这把锁续约成30s，如果操作成功，那么此时就会递归调用自己，再重新设置一个timeTask()，于是再过10s后又再设置一个timerTask，完成不停的续约</p>
<p>那么大家可以想一想，假设我们的线程出现了宕机他还会续约吗？当然不会，因为没有人再去调用renewExpiration这个方法，所以等到时间之后自然就释放了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">renewExpiration</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-type">ExpirationEntry</span> <span class="hljs-variable">ee</span> <span class="hljs-operator">=</span> EXPIRATION_RENEWAL_MAP.get(getEntryName());<br>    <span class="hljs-keyword">if</span> (ee == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-keyword">return</span>;<br>    &#125;<br>    <br>    <span class="hljs-type">Timeout</span> <span class="hljs-variable">task</span> <span class="hljs-operator">=</span> commandExecutor.getConnectionManager().newTimeout(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TimerTask</span>() &#123;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">(Timeout timeout)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>            <span class="hljs-type">ExpirationEntry</span> <span class="hljs-variable">ent</span> <span class="hljs-operator">=</span> EXPIRATION_RENEWAL_MAP.get(getEntryName());<br>            <span class="hljs-keyword">if</span> (ent == <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>            <span class="hljs-type">Long</span> <span class="hljs-variable">threadId</span> <span class="hljs-operator">=</span> ent.getFirstThreadId();<br>            <span class="hljs-keyword">if</span> (threadId == <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>            <br>            RFuture&lt;Boolean&gt; future = renewExpirationAsync(threadId);<br>            future.onComplete((res, e) -&gt; &#123;<br>                <span class="hljs-keyword">if</span> (e != <span class="hljs-literal">null</span>) &#123;<br>                    log.error(<span class="hljs-string">&quot;Can&#x27;t update lock &quot;</span> + getName() + <span class="hljs-string">&quot; expiration&quot;</span>, e);<br>                    <span class="hljs-keyword">return</span>;<br>                &#125;<br>                <br>                <span class="hljs-keyword">if</span> (res) &#123;<br>                    <span class="hljs-comment">// reschedule itself</span><br>                    renewExpiration();<br>                &#125;<br>            &#125;);<br>        &#125;<br>    &#125;, internalLockLeaseTime / <span class="hljs-number">3</span>, TimeUnit.MILLISECONDS);<br>    <br>    ee.setTimeout(task);<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="5-5-分布式锁-redission锁的MutiLock原理"><a href="#5-5-分布式锁-redission锁的MutiLock原理" class="headerlink" title="5.5 分布式锁-redission锁的MutiLock原理"></a>5.5 分布式锁-redission锁的MutiLock原理</h3><p>为了提高redis的可用性，我们会搭建集群或者主从，现在以主从为例</p>
<p>此时我们去写命令，写在主机上， 主机会将数据同步给从机，但是假设在主机还没有来得及把数据写入到从机去的时候，此时主机宕机，哨兵会发现主机宕机，并且选举一个slave变成master，而此时新的master中实际上并没有锁信息，此时锁信息就已经丢掉了。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302079.png" srcset="/img/loading.gif" lazyload alt="1653553998403"></p>
<p>为了解决这个问题，redission提出来了MutiLock锁，使用这把锁咱们就不使用主从了，每个节点的地位都是一样的， 这把锁加锁的逻辑需要写入到每一个主丛节点上，只有所有的服务器都写入成功，此时才是加锁成功，假设现在某个节点挂了，那么他去获得锁的时候，只要有一个节点拿不到，都不能算是加锁成功，就保证了加锁的可靠性。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302080.png" srcset="/img/loading.gif" lazyload alt="1653554055048"></p>
<p>那么MutiLock 加锁原理是什么呢？笔者画了一幅图来说明</p>
<p>当我们去设置了多个锁时，redission会将多个锁添加到一个集合中，然后用while循环去不停去尝试拿锁，但是会有一个总共的加锁时间，这个时间是用需要加锁的个数 * 1500ms ，假设有3个锁，那么时间就是4500ms，假设在这4500ms内，所有的锁都加锁成功， 那么此时才算是加锁成功，如果在4500ms有线程加锁失败，则会再次去进行重试.</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302081.png" srcset="/img/loading.gif" lazyload alt="1653553093967"></p>
<h2 id="6、秒杀优化"><a href="#6、秒杀优化" class="headerlink" title="6、秒杀优化"></a>6、秒杀优化</h2><h3 id="6-1-秒杀优化-异步秒杀思路"><a href="#6-1-秒杀优化-异步秒杀思路" class="headerlink" title="6.1 秒杀优化-异步秒杀思路"></a>6.1 秒杀优化-异步秒杀思路</h3><p>我们来回顾一下下单流程</p>
<p>当用户发起请求，此时会请求nginx，nginx会访问到tomcat，而tomcat中的程序，会进行串行操作，分成如下几个步骤</p>
<p>1、查询优惠卷</p>
<p>2、判断秒杀库存是否足够</p>
<p>3、查询订单</p>
<p>4、校验是否是一人一单</p>
<p>5、扣减库存</p>
<p>6、创建订单</p>
<p>在这六步操作中，又有很多操作是要去操作数据库的，而且还是一个线程串行执行， 这样就会导致我们的程序执行的很慢，所以我们需要异步程序执行，那么如何加速呢？</p>
<p>在这里笔者想给大家分享一下课程内没有的思路，看看有没有小伙伴这么想，比如，我们可不可以使用异步编排来做，或者说我开启N多线程，N多个线程，一个线程执行查询优惠卷，一个执行判断扣减库存，一个去创建订单等等，然后再统一做返回，这种做法和课程中有哪种好呢？答案是课程中的好，因为如果你采用我刚说的方式，如果访问的人很多，那么线程池中的线程可能一下子就被消耗完了，而且你使用上述方案，最大的特点在于，你觉得时效性会非常重要，但是你想想是吗？并不是，比如我只要确定他能做这件事，然后我后边慢慢做就可以了，我并不需要他一口气做完这件事，所以我们应当采用的是课程中，类似消息队列的方式来完成我们的需求，而不是使用线程池或者是异步编排的方式来完成这个需求。</p>
<blockquote>
<p>  总结：对线程池中的线程消耗较大，且提升的仅仅是做完的速度，其实只需要确定可以做就可以了。</p>
</blockquote>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302082.png" srcset="/img/loading.gif" lazyload alt="1653560986599"></p>
<p>优化方案：我们将耗时比较短的逻辑判断放入到redis中，比如是否库存足够，比如是否一人一单，这样的操作，只要这种逻辑可以完成，就意味着我们是一定可以下单完成的，我们只需要进行快速的逻辑判断，根本就不用等下单逻辑走完，我们直接给用户返回成功， 再在后台开一个线程，后台线程慢慢的去执行queue里边的消息，这样程序不就超级快了吗？而且也不用担心线程池消耗殆尽的问题，因为这里我们的程序中并没有手动使用任何线程池，当然这里边有两个难点</p>
<p>第一个难点是我们怎么在redis中去快速校验一人一单，还有库存判断</p>
<p>第二个难点是由于我们校验和tomct下单是两个线程，那么我们如何知道到底哪个单他最后是否成功，或者是下单完成，为了完成这件事我们在redis操作完之后，我们会将一些信息返回给前端，同时也会把这些信息丢到异步queue中去，后续操作中，可以通过这个id来查询我们tomcat中的下单逻辑是否完成了。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302083.png" srcset="/img/loading.gif" lazyload alt="1653561657295"></p>
<p>我们现在来看看整体思路：当用户下单之后，判断库存是否充足只需要到redis中去根据key找对应stock的value是否大于0即可，如果不充足，则直接结束，如果充足，继续在redis中判断用户是否可以下单，如果set集合中没有这条数据，说明他可以下单，如果set集合中没有这条记录，则将userId和优惠卷存入到redis中，并且返回0，整个过程需要保证是原子性的，我们可以使用lua来操作。</p>
<p>当以上判断逻辑走完之后，我们可以判断当前redis中返回的结果是否是0 ，如果是0，则表示可以下单，则将之前说的信息存入到到queue中去，然后返回，然后再来个线程异步的下单，前端可以通过返回的订单id来判断是否下单成功。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302084.png" srcset="/img/loading.gif" lazyload alt="1653562234886"></p>
<h3 id="6-2-秒杀优化-Redis完成秒杀资格判断"><a href="#6-2-秒杀优化-Redis完成秒杀资格判断" class="headerlink" title="6.2 秒杀优化-Redis完成秒杀资格判断"></a>6.2 秒杀优化-Redis完成秒杀资格判断</h3><p>需求：</p>
<ul>
<li><p>新增秒杀优惠券的同时，将优惠券信息保存到Redis中（）</p>
</li>
<li><p>基于Lua脚本，判断秒杀库存、一人一单，决定用户是否抢购成功</p>
</li>
<li><p>如果抢购成功，将优惠券id和用户id封装后存入阻塞队列</p>
</li>
<li><p>开启线程任务，不断从阻塞队列中获取信息，实现异步下单功能</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302085.png" srcset="/img/loading.gif" lazyload alt="1656080546603"></p>
</li>
</ul>
<p>VoucherServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-meta">@Transactional</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addSeckillVoucher</span><span class="hljs-params">(Voucher voucher)</span> &#123;<br>    <span class="hljs-comment">// 保存优惠券</span><br>    save(voucher);<br>    <span class="hljs-comment">// 保存秒杀信息</span><br>    <span class="hljs-type">SeckillVoucher</span> <span class="hljs-variable">seckillVoucher</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SeckillVoucher</span>();<br>    seckillVoucher.setVoucherId(voucher.getId());<br>    seckillVoucher.setStock(voucher.getStock());<br>    seckillVoucher.setBeginTime(voucher.getBeginTime());<br>    seckillVoucher.setEndTime(voucher.getEndTime());<br>    seckillVoucherService.save(seckillVoucher);<br>    <span class="hljs-comment">// 保存秒杀库存到Redis中</span><br>    <span class="hljs-comment">//SECKILL_STOCK_KEY 这个变量定义在RedisConstans中</span><br>    <span class="hljs-comment">//private static final String SECKILL_STOCK_KEY =&quot;seckill:stock:&quot;</span><br>    stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());<br>&#125;<br></code></pre></td></tr></table></figure>

<p>完整lua表达式</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-comment">-- 1.参数列表</span><br><span class="hljs-comment">-- 1.1.优惠券id</span><br><span class="hljs-keyword">local</span> voucherId = ARGV[<span class="hljs-number">1</span>]<br><span class="hljs-comment">-- 1.2.用户id</span><br><span class="hljs-keyword">local</span> userId = ARGV[<span class="hljs-number">2</span>]<br><span class="hljs-comment">-- 1.3.订单id</span><br><span class="hljs-keyword">local</span> orderId = ARGV[<span class="hljs-number">3</span>]<br><br><span class="hljs-comment">-- 2.数据key</span><br><span class="hljs-comment">-- 2.1.库存key</span><br><span class="hljs-keyword">local</span> stockKey = <span class="hljs-string">&#x27;seckill:stock:&#x27;</span> .. voucherId<br><span class="hljs-comment">-- 2.2.订单key</span><br><span class="hljs-keyword">local</span> orderKey = <span class="hljs-string">&#x27;seckill:order:&#x27;</span> .. voucherId<br><br><span class="hljs-comment">-- 3.脚本业务</span><br><span class="hljs-comment">-- 3.1.判断库存是否充足 get stockKey</span><br><span class="hljs-keyword">if</span>(<span class="hljs-built_in">tonumber</span>(redis.call(<span class="hljs-string">&#x27;get&#x27;</span>, stockKey)) &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">then</span><br>    <span class="hljs-comment">-- 3.2.库存不足，返回1</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span><br><span class="hljs-keyword">end</span><br><span class="hljs-comment">-- 3.2.判断用户是否下单 SISMEMBER orderKey userId</span><br><span class="hljs-keyword">if</span>(redis.call(<span class="hljs-string">&#x27;sismember&#x27;</span>, orderKey, userId) == <span class="hljs-number">1</span>) <span class="hljs-keyword">then</span><br>    <span class="hljs-comment">-- 3.3.存在，说明是重复下单，返回2</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span><br><span class="hljs-keyword">end</span><br><span class="hljs-comment">-- 3.4.扣库存 incrby stockKey -1</span><br>redis.call(<span class="hljs-string">&#x27;incrby&#x27;</span>, stockKey, <span class="hljs-number">-1</span>)<br><span class="hljs-comment">-- 3.5.下单（保存用户）sadd orderKey userId</span><br>redis.call(<span class="hljs-string">&#x27;sadd&#x27;</span>, orderKey, userId)<br><span class="hljs-comment">-- 3.6.发送消息到队列中， XADD stream.orders * k1 v1 k2 v2 ...</span><br>redis.call(<span class="hljs-string">&#x27;xadd&#x27;</span>, <span class="hljs-string">&#x27;stream.orders&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>, <span class="hljs-string">&#x27;userId&#x27;</span>, userId, <span class="hljs-string">&#x27;voucherId&#x27;</span>, voucherId, <span class="hljs-string">&#x27;id&#x27;</span>, orderId)<br><span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br></code></pre></td></tr></table></figure>

<p>当以上lua表达式执行完毕后，剩下的就是根据步骤3,4来执行我们接下来的任务了</p>
<p>VoucherOrderServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>    <span class="hljs-comment">//获取用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>    <span class="hljs-comment">// 1.执行lua脚本</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> stringRedisTemplate.execute(<br>            SECKILL_SCRIPT,<br>            Collections.emptyList(),<br>            voucherId.toString(), userId.toString(), String.valueOf(orderId)<br>    );<br>    <span class="hljs-type">int</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> result.intValue();<br>    <span class="hljs-comment">// 2.判断结果是否为0</span><br>    <span class="hljs-keyword">if</span> (r != <span class="hljs-number">0</span>) &#123;<br>        <span class="hljs-comment">// 2.1.不为0 ，代表没有购买资格</span><br>        <span class="hljs-keyword">return</span> Result.fail(r == <span class="hljs-number">1</span> ? <span class="hljs-string">&quot;库存不足&quot;</span> : <span class="hljs-string">&quot;不能重复下单&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">//TODO 保存阻塞队列</span><br>    <span class="hljs-comment">// 3.返回订单id</span><br>    <span class="hljs-keyword">return</span> Result.ok(orderId);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="6-3-秒杀优化-基于阻塞队列实现秒杀优化"><a href="#6-3-秒杀优化-基于阻塞队列实现秒杀优化" class="headerlink" title="6.3 秒杀优化-基于阻塞队列实现秒杀优化"></a>6.3 秒杀优化-基于阻塞队列实现秒杀优化</h3><p>VoucherOrderServiceImpl</p>
<p>修改下单动作，现在我们去下单时，是通过lua表达式去原子执行判断逻辑，如果判断我出来不为0 ，则要么是库存不足，要么是重复下单，返回错误信息，如果是0，则把下单的逻辑保存到队列中去，然后异步执行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//异步处理线程池</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">ExecutorService</span> <span class="hljs-variable">SECKILL_ORDER_EXECUTOR</span> <span class="hljs-operator">=</span> Executors.newSingleThreadExecutor();<br><br><span class="hljs-comment">//在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的</span><br><span class="hljs-meta">@PostConstruct</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">init</span><span class="hljs-params">()</span> &#123;<br>   SECKILL_ORDER_EXECUTOR.submit(<span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrderHandler</span>());<br>&#125;<br><span class="hljs-comment">// 用于线程池处理的任务</span><br><span class="hljs-comment">// 当初始化完毕后，就会去从对列中去拿信息</span><br> <span class="hljs-keyword">private</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">VoucherOrderHandler</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Runnable</span>&#123;<br><br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>            <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>)&#123;<br>                <span class="hljs-keyword">try</span> &#123;<br>                    <span class="hljs-comment">// 1.获取队列中的订单信息</span><br>                    <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> orderTasks.take();<br>                    <span class="hljs-comment">// 2.创建订单</span><br>                    handleVoucherOrder(voucherOrder);<br>                &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>                    log.error(<span class="hljs-string">&quot;处理订单异常&quot;</span>, e);<br>                &#125;<br>          	 &#125;<br>        &#125;<br>     <br>       <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">handleVoucherOrder</span><span class="hljs-params">(VoucherOrder voucherOrder)</span> &#123;<br>            <span class="hljs-comment">//1.获取用户</span><br>            <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> voucherOrder.getUserId();<br>            <span class="hljs-comment">// 2.创建锁对象</span><br>            <span class="hljs-type">RLock</span> <span class="hljs-variable">redisLock</span> <span class="hljs-operator">=</span> redissonClient.getLock(<span class="hljs-string">&quot;lock:order:&quot;</span> + userId);<br>            <span class="hljs-comment">// 3.尝试获取锁</span><br>            <span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> redisLock.lock();<br>            <span class="hljs-comment">// 4.判断是否获得锁成功</span><br>            <span class="hljs-keyword">if</span> (!isLock) &#123;<br>                <span class="hljs-comment">// 获取锁失败，直接返回失败或者重试</span><br>                log.error(<span class="hljs-string">&quot;不允许重复下单！&quot;</span>);<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>            <span class="hljs-keyword">try</span> &#123;<br>				<span class="hljs-comment">//注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效</span><br>                proxy.createVoucherOrder(voucherOrder);<br>            &#125; <span class="hljs-keyword">finally</span> &#123;<br>                <span class="hljs-comment">// 释放锁</span><br>                redisLock.unlock();<br>            &#125;<br>    &#125;<br>     <span class="hljs-comment">//a</span><br>	<span class="hljs-keyword">private</span> BlockingQueue&lt;VoucherOrder&gt; orderTasks = <span class="hljs-keyword">new</span>  <span class="hljs-title class_">ArrayBlockingQueue</span>&lt;&gt;(<span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>);<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">seckillVoucher</span><span class="hljs-params">(Long voucherId)</span> &#123;<br>        <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>        <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>        <span class="hljs-comment">// 1.执行lua脚本</span><br>        <span class="hljs-type">Long</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> stringRedisTemplate.execute(<br>                SECKILL_SCRIPT,<br>                Collections.emptyList(),<br>                voucherId.toString(), userId.toString(), String.valueOf(orderId)<br>        );<br>        <span class="hljs-type">int</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> result.intValue();<br>        <span class="hljs-comment">// 2.判断结果是否为0</span><br>        <span class="hljs-keyword">if</span> (r != <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-comment">// 2.1.不为0 ，代表没有购买资格</span><br>            <span class="hljs-keyword">return</span> Result.fail(r == <span class="hljs-number">1</span> ? <span class="hljs-string">&quot;库存不足&quot;</span> : <span class="hljs-string">&quot;不能重复下单&quot;</span>);<br>        &#125;<br>        <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>();<br>        <span class="hljs-comment">// 2.3.订单id</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">orderId</span> <span class="hljs-operator">=</span> redisIdWorker.nextId(<span class="hljs-string">&quot;order&quot;</span>);<br>        voucherOrder.setId(orderId);<br>        <span class="hljs-comment">// 2.4.用户id</span><br>        voucherOrder.setUserId(userId);<br>        <span class="hljs-comment">// 2.5.代金券id</span><br>        voucherOrder.setVoucherId(voucherId);<br>        <span class="hljs-comment">// 2.6.放入阻塞队列</span><br>        orderTasks.add(voucherOrder);<br>        <span class="hljs-comment">//3.获取代理对象</span><br>         proxy = (IVoucherOrderService)AopContext.currentProxy();<br>        <span class="hljs-comment">//4.返回订单id</span><br>        <span class="hljs-keyword">return</span> Result.ok(orderId);<br>    &#125;<br>     <br>      <span class="hljs-meta">@Transactional</span><br>    <span class="hljs-keyword">public</span>  <span class="hljs-keyword">void</span> <span class="hljs-title function_">createVoucherOrder</span><span class="hljs-params">(VoucherOrder voucherOrder)</span> &#123;<br>        <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> voucherOrder.getUserId();<br>        <span class="hljs-comment">// 5.1.查询订单</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherOrder.getVoucherId()).count();<br>        <span class="hljs-comment">// 5.2.判断是否存在</span><br>        <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-comment">// 用户已经购买过了</span><br>           log.error(<span class="hljs-string">&quot;用户已经购买过了&quot;</span>);<br>           <span class="hljs-keyword">return</span> ;<br>        &#125;<br><br>        <span class="hljs-comment">// 6.扣减库存</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">success</span> <span class="hljs-operator">=</span> seckillVoucherService.update()<br>                .setSql(<span class="hljs-string">&quot;stock = stock - 1&quot;</span>) <span class="hljs-comment">// set stock = stock - 1</span><br>                .eq(<span class="hljs-string">&quot;voucher_id&quot;</span>, voucherOrder.getVoucherId()).gt(<span class="hljs-string">&quot;stock&quot;</span>, <span class="hljs-number">0</span>) <span class="hljs-comment">// where id = ? and stock &gt; 0</span><br>                .update();<br>        <span class="hljs-keyword">if</span> (!success) &#123;<br>            <span class="hljs-comment">// 扣减失败</span><br>            log.error(<span class="hljs-string">&quot;库存不足&quot;</span>);<br>            <span class="hljs-keyword">return</span> ;<br>        &#125;<br>        save(voucherOrder);<br>    &#125;<br><br></code></pre></td></tr></table></figure>

<p><strong>小总结：</strong></p>
<p>秒杀业务的优化思路是什么？</p>
<ul>
<li>先利用Redis完成库存余量、一人一单判断，完成抢单业务</li>
<li>再将下单业务放入阻塞队列，利用独立线程异步下单</li>
<li>基于阻塞队列的异步秒杀存在哪些问题？<ul>
<li>内存限制问题</li>
<li>数据安全问题</li>
</ul>
</li>
</ul>
<h2 id="7、Redis消息队列"><a href="#7、Redis消息队列" class="headerlink" title="7、Redis消息队列"></a>7、Redis消息队列</h2><h3 id="7-1-Redis消息队列-认识消息队列"><a href="#7-1-Redis消息队列-认识消息队列" class="headerlink" title="7.1 Redis消息队列-认识消息队列"></a>7.1 Redis消息队列-认识消息队列</h3><p>什么是消息队列：字面意思就是存放消息的队列。最简单的消息队列模型包括3个角色：</p>
<ul>
<li>消息队列：存储和管理消息，也被称为消息代理（Message Broker）</li>
<li>生产者：发送消息到消息队列</li>
<li>消费者：从消息队列获取消息并处理消息</li>
</ul>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302086.png" srcset="/img/loading.gif" lazyload alt="1653574849336"></p>
<p>使用队列的好处在于 <strong>解耦：</strong>所谓解耦，举一个生活中的例子就是：快递员(生产者)把快递放到快递柜里边(Message Queue)去，我们(消费者)从快递柜里边去拿东西，这就是一个异步，如果耦合，那么这个快递员相当于直接把快递交给你，这事固然好，但是万一你不在家，那么快递员就会一直等你，这就浪费了快递员的时间，所以这种思想在我们日常开发中，是非常有必要的。</p>
<p>这种场景在我们秒杀中就变成了：我们下单之后，利用redis去进行校验下单条件，再通过队列把消息发送出去，然后再启动一个线程去消费这个消息，完成解耦，同时也加快我们的响应速度。</p>
<p>这里我们可以使用一些现成的mq，比如kafka，rabbitmq等等，但是呢，如果没有安装mq，我们也可以直接使用redis提供的mq方案，降低我们的部署和学习成本。</p>
<h3 id="7-2-Redis消息队列-基于List实现消息队列"><a href="#7-2-Redis消息队列-基于List实现消息队列" class="headerlink" title="7.2 Redis消息队列-基于List实现消息队列"></a>7.2 Redis消息队列-基于List实现消息队列</h3><p><strong>基于List结构模拟消息队列</strong></p>
<p>消息队列（Message Queue），字面意思就是存放消息的队列。而Redis的list数据结构是一个双向链表，很容易模拟出队列效果。</p>
<p>队列是入口和出口不在一边，因此我们可以利用：LPUSH 结合 RPOP、或者 RPUSH 结合 LPOP来实现。<br>不过要注意的是，当队列中没有消息时RPOP或LPOP操作会返回null，并不像JVM的阻塞队列那样会阻塞并等待消息。因此这里应该使用BRPOP或者BLPOP来实现阻塞效果。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302087.png" srcset="/img/loading.gif" lazyload alt="1653575176451"></p>
<p>基于List的消息队列有哪些优缺点？<br>优点：</p>
<ul>
<li>利用Redis存储，不受限于JVM内存上限</li>
<li>基于Redis的持久化机制，数据安全性有保证</li>
<li>可以满足消息有序性</li>
</ul>
<p>缺点：</p>
<ul>
<li>无法避免消息丢失</li>
<li>只支持单消费者</li>
</ul>
<h3 id="7-3-Redis消息队列-基于PubSub的消息队列"><a href="#7-3-Redis消息队列-基于PubSub的消息队列" class="headerlink" title="7.3 Redis消息队列-基于PubSub的消息队列"></a>7.3 Redis消息队列-基于PubSub的消息队列</h3><p>PubSub（发布订阅）是Redis2.0版本引入的消息传递模型。顾名思义，消费者可以订阅一个或多个channel，生产者向对应channel发送消息后，所有订阅者都能收到相关消息。</p>
<p> SUBSCRIBE channel [channel] ：订阅一个或多个频道<br> PUBLISH channel msg ：向一个频道发送消息<br> PSUBSCRIBE pattern[pattern] ：订阅与pattern格式匹配的所有频道</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302088.png" srcset="/img/loading.gif" lazyload alt="1653575506373"></p>
<p>基于PubSub的消息队列有哪些优缺点？<br>优点：</p>
<ul>
<li>采用发布订阅模型，支持多生产、多消费</li>
</ul>
<p>缺点：</p>
<ul>
<li>不支持数据持久化</li>
<li>无法避免消息丢失</li>
<li>消息堆积有上限，超出时数据丢失</li>
</ul>
<h3 id="7-4-Redis消息队列-基于Stream的消息队列"><a href="#7-4-Redis消息队列-基于Stream的消息队列" class="headerlink" title="7.4 Redis消息队列-基于Stream的消息队列"></a>7.4 Redis消息队列-基于Stream的消息队列</h3><p>Stream 是 Redis 5.0 引入的一种新数据类型，可以实现一个功能非常完善的消息队列。</p>
<p>发送消息的命令：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302089.png" srcset="/img/loading.gif" lazyload alt="1653577301737"></p>
<p>例如：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302090.png" srcset="/img/loading.gif" lazyload alt="1653577349691"></p>
<p>读取消息的方式之一：XREAD</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302091.png" srcset="/img/loading.gif" lazyload alt="1653577445413"></p>
<p>例如，使用XREAD读取第一个消息：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302092.png" srcset="/img/loading.gif" lazyload alt="1653577643629"></p>
<p>XREAD阻塞方式，读取最新的消息：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302093.png" srcset="/img/loading.gif" lazyload alt="1653577659166"></p>
<p>在业务开发中，我们可以循环的调用XREAD阻塞方式来查询最新消息，从而实现持续监听队列的效果，伪代码如下</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs dart"><span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>)&#123;<br>	<span class="hljs-comment">//试读取队列中的消息，最多阻塞2秒</span><br>	<span class="hljs-built_in">Object</span> msg = redis.execute(<span class="hljs-string">&quot;XREAD COUNT I BLOCK 2000 STREAMS users $&quot;</span>);<br>	<span class="hljs-keyword">if</span>(msg == <span class="hljs-keyword">null</span>)&#123;<br>		<br>	&#125;<br>	<span class="hljs-comment">//处理消息</span><br>	handleMessage(msg);<br>&#125;<br></code></pre></td></tr></table></figure>



<p>注意：当我们指定起始ID为$时，代表读取最新的消息，如果我们处理一条消息的过程中，又有超过1条以上的消息到达队列，则下次获取时也只能获取到最新的一条，会出现漏读消息的问题。</p>
<p>STREAM类型消息队列的XREAD命令特点：</p>
<ul>
<li>消息可回溯</li>
<li>一个消息可以被多个消费者读取</li>
<li>可以阻塞读取</li>
<li>有消息漏读的风险</li>
</ul>
<h3 id="7-5-Redis消息队列-基于Stream的消息队列-消费者组"><a href="#7-5-Redis消息队列-基于Stream的消息队列-消费者组" class="headerlink" title="7.5 Redis消息队列-基于Stream的消息队列-消费者组"></a>7.5 Redis消息队列-基于Stream的消息队列-消费者组</h3><p>消费者组（Consumer Group）：将多个消费者划分到一个组中，监听同一个队列。具备下列特点：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302095.png" srcset="/img/loading.gif" lazyload alt="1653577801668"></p>
<p><strong>创建消费者组：</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">XGROUP CREATE key groupName ID [MKSTREAM]<br></code></pre></td></tr></table></figure>

<p>key：队列名称<br>groupName：消费者组名称<br>ID：起始ID标示，$代表队列中最后一个消息，0则代表队列中第一个消息<br>MKSTREAM：队列不存在时自动创建队列</p>
<p>其它常见命令：</p>
<p> <strong>删除指定的消费者组</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">XGROUP DESTORY key groupName<br></code></pre></td></tr></table></figure>

<p> <strong>给指定的消费者组添加消费者</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">XGROUP CREATECONSUMER key groupname consumername<br></code></pre></td></tr></table></figure>

<p> <strong>删除消费者组中的指定消费者</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">XGROUP DELCONSUMER key groupname consumername<br></code></pre></td></tr></table></figure>

<p><strong>从消费者组读取消息：</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] [NOACK] STREAMS key [key ...] ID [ID ...]<br></code></pre></td></tr></table></figure>

<ul>
<li>group：消费组名称</li>
<li>consumer：消费者名称，如果消费者不存在，会自动创建一个消费者</li>
<li>count：本次查询的最大数量</li>
<li>BLOCK milliseconds：当没有消息时最长等待时间</li>
<li>NOACK：无需手动ACK，获取到消息后自动确认</li>
<li>STREAMS key：指定队列名称</li>
<li>ID：获取消息的起始ID：<ul>
<li>“&gt;”：从下一个未消费的消息开始</li>
<li>其它：根据指定id从pending-list中获取已消费但未确认的消息，例如0，是从pending-list中的第一个消息开始</li>
</ul>
</li>
</ul>
<p>消费者监听消息的基本思路：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>)&#123;<br>	<span class="hljs-comment">// 尝试监听队列，使用阻塞模式，最长等待 2000 毫秒</span><br>	<span class="hljs-type">object</span> <span class="hljs-variable">msg</span> <span class="hljs-operator">=</span> redis.call(<span class="hljs-string">&quot;XRFADGROUP GROUP g1 C1 COUNT 1 BLCK 2000 STRFAMS S1 &gt;&quot;</span>);<br>    <span class="hljs-keyword">if</span>(msg == <span class="hljs-literal">null</span>)&#123;<br>    	<span class="hljs-comment">// null说明没有消息，继续下一次</span><br>    	<span class="hljs-keyword">continue</span>;<br>    &#125;<br>    <span class="hljs-keyword">try</span> &#123;<br>    	<span class="hljs-comment">// 处理消息，完成后需要ACK</span><br>    	handleMessage(msg);<br>    &#125; <span class="hljs-keyword">catch</span>(Exception e) &#123;<br>    	<span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>) &#123;<br>            <span class="hljs-comment">// 有异常，查看pendinglist中的异常并进行处理</span><br>    		<span class="hljs-type">Object</span> <span class="hljs-variable">msg</span> <span class="hljs-operator">=</span> redis.call(<span class="hljs-string">&quot;XREADGROUP GROUP g1 c1 COUNT 1 STREAMS s1 0&quot;</span>);<br>    		<span class="hljs-keyword">if</span> (msg == <span class="hljs-literal">null</span>) &#123; <span class="hljs-comment">// null说明没有异常消息，所有消息都已确认，结束循环</span><br>    			<span class="hljs-keyword">break</span>;<br>    		&#125;<br>            <span class="hljs-keyword">try</span> &#123;<br>                <span class="hljs-comment">//说明有异常消息，再次处理</span><br>                handleMessage(msg);<br>            &#125; <span class="hljs-keyword">catch</span>(Exception e) &#123;<br>                <span class="hljs-comment">// 再次出现异常，记录日志，继续循环</span><br>                <span class="hljs-keyword">continue</span>;<br>            &#125;<br>    	&#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>STREAM类型消息队列的XREADGROUP命令特点：</p>
<ul>
<li>消息可回溯</li>
<li>可以多消费者争抢消息，加快消费速度</li>
<li>可以阻塞读取</li>
<li>没有消息漏读的风险</li>
<li>有消息确认机制，保证消息至少被消费一次</li>
</ul>
<p>最后我们来个小对比</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302098.png" srcset="/img/loading.gif" lazyload alt="1653578560691"></p>
<h3 id="7-6-基于Redis的Stream结构作为消息队列，实现异步秒杀下单"><a href="#7-6-基于Redis的Stream结构作为消息队列，实现异步秒杀下单" class="headerlink" title="7.6 基于Redis的Stream结构作为消息队列，实现异步秒杀下单"></a>7.6 基于Redis的Stream结构作为消息队列，实现异步秒杀下单</h3><p>需求：</p>
<ul>
<li>创建一个Stream类型的消息队列，名为stream.orders</li>
<li>修改之前的秒杀下单Lua脚本，在认定有抢购资格后，直接向stream.orders中添加消息，内容包含voucherId、userId、orderId</li>
<li>项目启动时，开启一个线程任务，尝试获取stream.orders中的消息，完成下单\</li>
</ul>
<p>修改lua表达式,新增3.6 </p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302099.png" srcset="/img/loading.gif" lazyload alt="1656082824939"></p>
<p>VoucherOrderServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">VoucherOrderHandler</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Runnable</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                <span class="hljs-comment">// 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 &gt;</span><br>                List&lt;MapRecord&lt;String, Object, Object&gt;&gt; list = stringRedisTemplate.opsForStream().read(<br>                    Consumer.from(<span class="hljs-string">&quot;g1&quot;</span>, <span class="hljs-string">&quot;c1&quot;</span>),<br>                    StreamReadOptions.empty().count(<span class="hljs-number">1</span>).block(Duration.ofSeconds(<span class="hljs-number">2</span>)),<br>                    StreamOffset.create(<span class="hljs-string">&quot;stream.orders&quot;</span>, ReadOffset.lastConsumed())<br>                );<br>                <span class="hljs-comment">// 2.判断订单信息是否为空</span><br>                <span class="hljs-keyword">if</span> (list == <span class="hljs-literal">null</span> || list.isEmpty()) &#123;<br>                    <span class="hljs-comment">// 如果为null，说明没有消息，继续下一次循环</span><br>                    <span class="hljs-keyword">continue</span>;<br>                &#125;<br>                <span class="hljs-comment">// 解析数据</span><br>                MapRecord&lt;String, Object, Object&gt; record = list.get(<span class="hljs-number">0</span>);<br>                Map&lt;Object, Object&gt; value = record.getValue();<br>                <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> BeanUtil.fillBeanWithMap(value, <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>(), <span class="hljs-literal">true</span>);<br>                <span class="hljs-comment">// 3.创建订单</span><br>                createVoucherOrder(voucherOrder);<br>                <span class="hljs-comment">// 4.确认消息 XACK</span><br>                stringRedisTemplate.opsForStream().acknowledge(<span class="hljs-string">&quot;s1&quot;</span>, <span class="hljs-string">&quot;g1&quot;</span>, record.getId());<br>            &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>                log.error(<span class="hljs-string">&quot;处理订单异常&quot;</span>, e);<br>                <span class="hljs-comment">//处理异常消息</span><br>                handlePendingList();<br>            &#125;<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">handlePendingList</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                <span class="hljs-comment">// 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0</span><br>                List&lt;MapRecord&lt;String, Object, Object&gt;&gt; list = stringRedisTemplate.opsForStream().read(<br>                    Consumer.from(<span class="hljs-string">&quot;g1&quot;</span>, <span class="hljs-string">&quot;c1&quot;</span>),<br>                    StreamReadOptions.empty().count(<span class="hljs-number">1</span>),<br>                    StreamOffset.create(<span class="hljs-string">&quot;stream.orders&quot;</span>, ReadOffset.from(<span class="hljs-string">&quot;0&quot;</span>))<br>                );<br>                <span class="hljs-comment">// 2.判断订单信息是否为空</span><br>                <span class="hljs-keyword">if</span> (list == <span class="hljs-literal">null</span> || list.isEmpty()) &#123;<br>                    <span class="hljs-comment">// 如果为null，说明没有异常消息，结束循环</span><br>                    <span class="hljs-keyword">break</span>;<br>                &#125;<br>                <span class="hljs-comment">// 解析数据</span><br>                MapRecord&lt;String, Object, Object&gt; record = list.get(<span class="hljs-number">0</span>);<br>                Map&lt;Object, Object&gt; value = record.getValue();<br>                <span class="hljs-type">VoucherOrder</span> <span class="hljs-variable">voucherOrder</span> <span class="hljs-operator">=</span> BeanUtil.fillBeanWithMap(value, <span class="hljs-keyword">new</span> <span class="hljs-title class_">VoucherOrder</span>(), <span class="hljs-literal">true</span>);<br>                <span class="hljs-comment">// 3.创建订单</span><br>                createVoucherOrder(voucherOrder);<br>                <span class="hljs-comment">// 4.确认消息 XACK</span><br>                stringRedisTemplate.opsForStream().acknowledge(<span class="hljs-string">&quot;s1&quot;</span>, <span class="hljs-string">&quot;g1&quot;</span>, record.getId());<br>            &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>                log.error(<span class="hljs-string">&quot;处理pendding订单异常&quot;</span>, e);<br>                <span class="hljs-keyword">try</span>&#123;<br>                    Thread.sleep(<span class="hljs-number">20</span>);<br>                &#125;<span class="hljs-keyword">catch</span>(Exception e)&#123;<br>                    e.printStackTrace();<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="8、达人探店"><a href="#8、达人探店" class="headerlink" title="8、达人探店"></a>8、达人探店</h2><h3 id="8-1、达人探店-发布探店笔记"><a href="#8-1、达人探店-发布探店笔记" class="headerlink" title="8.1、达人探店-发布探店笔记"></a>8.1、达人探店-发布探店笔记</h3><p>发布探店笔记</p>
<p>探店笔记类似点评网站的评价，往往是图文结合。对应的表有两个：<br>tb_blog：探店笔记表，包含笔记中的标题、文字、图片等<br>tb_blog_comments：其他用户对探店笔记的评价</p>
<p><strong>具体发布流程</strong></p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302100.png" srcset="/img/loading.gif" lazyload alt="1653578992639"></p>
<p>上传接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Slf4j</span><br><span class="hljs-meta">@RestController</span><br><span class="hljs-meta">@RequestMapping(&quot;upload&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UploadController</span> &#123;<br><br>    <span class="hljs-meta">@PostMapping(&quot;blog&quot;)</span><br>    <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">uploadImage</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(&quot;file&quot;)</span> MultipartFile image)</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 获取原始文件名称</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">originalFilename</span> <span class="hljs-operator">=</span> image.getOriginalFilename();<br>            <span class="hljs-comment">// 生成新文件名</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">fileName</span> <span class="hljs-operator">=</span> createNewFileName(originalFilename);<br>            <span class="hljs-comment">// 保存文件</span><br>            image.transferTo(<span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(SystemConstants.IMAGE_UPLOAD_DIR, fileName));<br>            <span class="hljs-comment">// 返回结果</span><br>            log.debug(<span class="hljs-string">&quot;文件上传成功，&#123;&#125;&quot;</span>, fileName);<br>            <span class="hljs-keyword">return</span> Result.ok(fileName);<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">&quot;文件上传失败&quot;</span>, e);<br>        &#125;<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>注意：同学们在操作时，需要修改SystemConstants.IMAGE_UPLOAD_DIR 自己图片所在的地址，在实际开发中图片一般会放在nginx上或者是云存储上。</p>
<p>BlogController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RestController</span><br><span class="hljs-meta">@RequestMapping(&quot;/blog&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">BlogController</span> &#123;<br><br>    <span class="hljs-meta">@Resource</span><br>    <span class="hljs-keyword">private</span> IBlogService blogService;<br><br>    <span class="hljs-meta">@PostMapping</span><br>    <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">saveBlog</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Blog blog)</span> &#123;<br>        <span class="hljs-comment">//获取登录用户</span><br>        <span class="hljs-type">UserDTO</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> UserHolder.getUser();<br>        blog.setUpdateTime(user.getId());<br>        <span class="hljs-comment">//保存探店博文</span><br>        blogService.saveBlog(blog);<br>        <span class="hljs-comment">//返回id</span><br>        <span class="hljs-keyword">return</span> Result.ok(blog.getId());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="8-2-达人探店-查看探店笔记"><a href="#8-2-达人探店-查看探店笔记" class="headerlink" title="8.2 达人探店-查看探店笔记"></a>8.2 达人探店-查看探店笔记</h3><p>实现查看发布探店笔记的接口</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302101.png" srcset="/img/loading.gif" lazyload alt="1653579931626"></p>
<p>实现代码：</p>
<p>BlogServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogById</span><span class="hljs-params">(Long id)</span> &#123;<br>    <span class="hljs-comment">// 1.查询blog</span><br>    <span class="hljs-type">Blog</span> <span class="hljs-variable">blog</span> <span class="hljs-operator">=</span> getById(id);<br>    <span class="hljs-keyword">if</span> (blog == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;笔记不存在！&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 2.查询blog有关的用户</span><br>    queryBlogUser(blog);<br>  <br>    <span class="hljs-keyword">return</span> Result.ok(blog);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="8-3-达人探店-点赞功能"><a href="#8-3-达人探店-点赞功能" class="headerlink" title="8.3 达人探店-点赞功能"></a>8.3 达人探店-点赞功能</h3><p>初始代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/likes/&#123;id&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogLikes</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> Long id)</span> &#123;<br>    <span class="hljs-comment">//修改点赞数量</span><br>    blogService.update().setSql(<span class="hljs-string">&quot;liked = liked +1 &quot;</span>).eq(<span class="hljs-string">&quot;id&quot;</span>,id).update();<br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>问题分析：这种方式会导致一个用户无限点赞，明显是不合理的</p>
<p>造成这个问题的原因是，我们现在的逻辑，发起请求只是给数据库+1，所以才会出现这个问题</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302102.png" srcset="/img/loading.gif" lazyload alt="1653581590453"></p>
<p>完善点赞功能</p>
<p>需求：</p>
<ul>
<li>同一个用户只能点赞一次，再次点击则取消点赞</li>
<li>如果当前用户已经点赞，则点赞按钮高亮显示（前端已实现，判断字段Blog类的isLike属性）</li>
</ul>
<p>实现步骤：</p>
<ul>
<li>给Blog类中添加一个isLike字段，标示是否被当前用户点赞</li>
<li>修改点赞功能，利用Redis的set集合判断是否点赞过，未点赞过则点赞数+1，已点赞过则点赞数-1</li>
<li>修改根据id查询Blog的业务，判断当前登录用户是否点赞过，赋值给isLike字段</li>
<li>修改分页查询Blog业务，判断当前登录用户是否点赞过，赋值给isLike字段</li>
</ul>
<p>为什么采用set集合：</p>
<p>因为我们的数据是不能重复的，当用户操作过之后，无论他怎么操作，都是</p>
<p>具体步骤：</p>
<p>1、在Blog 添加一个字段</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@TableField(exist = false)</span><br><span class="hljs-keyword">private</span> Boolean isLike;<br></code></pre></td></tr></table></figure>

<p>2、修改代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br>   <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">likeBlog</span><span class="hljs-params">(Long id)</span>&#123;<br>       <span class="hljs-comment">// 1.获取登录用户</span><br>       <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>       <span class="hljs-comment">// 2.判断当前登录用户是否已经点赞</span><br>       <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> BLOG_LIKED_KEY + id;<br>       <span class="hljs-type">Boolean</span> <span class="hljs-variable">isMember</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForSet().isMember(key, userId.toString());<br>       <span class="hljs-keyword">if</span>(BooleanUtil.isFalse(isMember))&#123;<br>            <span class="hljs-comment">//3.如果未点赞，可以点赞</span><br>           <span class="hljs-comment">//3.1 数据库点赞数+1</span><br>           <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> update().setSql(<span class="hljs-string">&quot;liked = liked + 1&quot;</span>).eq(<span class="hljs-string">&quot;id&quot;</span>, id).update();<br>           <span class="hljs-comment">//3.2 保存用户到Redis的set集合</span><br>           <span class="hljs-keyword">if</span>(isSuccess)&#123;<br>               stringRedisTemplate.opsForSet().add(key,userId.toString());<br>           &#125;<br>       &#125;<span class="hljs-keyword">else</span>&#123;<br>            <span class="hljs-comment">//4.如果已点赞，取消点赞</span><br>           <span class="hljs-comment">//4.1 数据库点赞数-1</span><br>           <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> update().setSql(<span class="hljs-string">&quot;liked = liked - 1&quot;</span>).eq(<span class="hljs-string">&quot;id&quot;</span>, id).update();<br>           <span class="hljs-comment">//4.2 把用户从Redis的set集合移除</span><br>           <span class="hljs-keyword">if</span>(isSuccess)&#123;<br>               stringRedisTemplate.opsForSet().remove(key,userId.toString());<br>           &#125;<br>       &#125;<br></code></pre></td></tr></table></figure>

<h3 id="8-4-达人探店-点赞排行榜"><a href="#8-4-达人探店-点赞排行榜" class="headerlink" title="8.4 达人探店-点赞排行榜"></a>8.4 达人探店-点赞排行榜</h3><p>在探店笔记的详情页面，应该把给该笔记点赞的人显示出来，比如最早点赞的TOP5，形成点赞排行榜：</p>
<p>之前的点赞是放到set集合，但是set集合是不能排序的，所以这个时候，咱们可以采用一个可以排序的set集合，就是咱们的sortedSet</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302103.png" srcset="/img/loading.gif" lazyload alt="1653805077118"></p>
<p>我们接下来来对比一下这些集合的区别是什么</p>
<p>所有点赞的人，需要是唯一的，所以我们应当使用set或者是sortedSet</p>
<p>其次我们需要排序，就可以直接锁定使用sortedSet啦</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302104.png" srcset="/img/loading.gif" lazyload alt="1653805203758"></p>
<p>修改代码</p>
<p>BlogServiceImpl</p>
<p>点赞逻辑代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br> <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">likeBlog</span><span class="hljs-params">(Long id)</span> &#123;<br>     <span class="hljs-comment">// 1.获取登录用户</span><br>     <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>     <span class="hljs-comment">// 2.判断当前登录用户是否已经点赞</span><br>     <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> BLOG_LIKED_KEY + id;<br>     <span class="hljs-type">Double</span> <span class="hljs-variable">score</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForZSet().score(key, userId.toString());<br>     <span class="hljs-keyword">if</span> (score == <span class="hljs-literal">null</span>) &#123;<br>         <span class="hljs-comment">// 3.如果未点赞，可以点赞</span><br>         <span class="hljs-comment">// 3.1.数据库点赞数 + 1</span><br>         <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> update().setSql(<span class="hljs-string">&quot;liked = liked + 1&quot;</span>).eq(<span class="hljs-string">&quot;id&quot;</span>, id).update();<br>         <span class="hljs-comment">// 3.2.保存用户到Redis的set集合  zadd key value score</span><br>         <span class="hljs-keyword">if</span> (isSuccess) &#123;<br>             stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());<br>         &#125;<br>     &#125; <span class="hljs-keyword">else</span> &#123;<br>         <span class="hljs-comment">// 4.如果已点赞，取消点赞</span><br>         <span class="hljs-comment">// 4.1.数据库点赞数 -1</span><br>         <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> update().setSql(<span class="hljs-string">&quot;liked = liked - 1&quot;</span>).eq(<span class="hljs-string">&quot;id&quot;</span>, id).update();<br>         <span class="hljs-comment">// 4.2.把用户从Redis的set集合移除</span><br>         <span class="hljs-keyword">if</span> (isSuccess) &#123;<br>             stringRedisTemplate.opsForZSet().remove(key, userId.toString());<br>         &#125;<br>     &#125;<br>     <span class="hljs-keyword">return</span> Result.ok();<br> &#125;<br><br><br> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">isBlogLiked</span><span class="hljs-params">(Blog blog)</span> &#123;<br>     <span class="hljs-comment">// 1.获取登录用户</span><br>     <span class="hljs-type">UserDTO</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> UserHolder.getUser();<br>     <span class="hljs-keyword">if</span> (user == <span class="hljs-literal">null</span>) &#123;<br>         <span class="hljs-comment">// 用户未登录，无需查询是否点赞</span><br>         <span class="hljs-keyword">return</span>;<br>     &#125;<br>     <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> user.getId();<br>     <span class="hljs-comment">// 2.判断当前登录用户是否已经点赞</span><br>     <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;blog:liked:&quot;</span> + blog.getId();<br>     <span class="hljs-type">Double</span> <span class="hljs-variable">score</span> <span class="hljs-operator">=</span> stringRedisTemplate.opsForZSet().score(key, userId.toString());<br>     blog.setIsLike(score != <span class="hljs-literal">null</span>);<br> &#125;<br></code></pre></td></tr></table></figure>

<p>点赞列表查询列表</p>
<p>BlogController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/likes/&#123;id&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogLikes</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> Long id)</span> &#123;<br><br>    <span class="hljs-keyword">return</span> blogService.queryBlogLikes(id);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>BlogService</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogLikes</span><span class="hljs-params">(Long id)</span> &#123;<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> BLOG_LIKED_KEY + id;<br>    <span class="hljs-comment">// 1.查询top5的点赞用户 zrange key 0 4</span><br>    Set&lt;String&gt; top5 = stringRedisTemplate.opsForZSet().range(key, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>);<br>    <span class="hljs-keyword">if</span> (top5 == <span class="hljs-literal">null</span> || top5.isEmpty()) &#123;<br>        <span class="hljs-keyword">return</span> Result.ok(Collections.emptyList());<br>    &#125;<br>    <span class="hljs-comment">// 2.解析出其中的用户id</span><br>    List&lt;Long&gt; ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());<br>    <span class="hljs-type">String</span> <span class="hljs-variable">idStr</span> <span class="hljs-operator">=</span> StrUtil.join(<span class="hljs-string">&quot;,&quot;</span>, ids);<br>    <span class="hljs-comment">// 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)</span><br>    List&lt;UserDTO&gt; userDTOS = userService.query()<br>            .in(<span class="hljs-string">&quot;id&quot;</span>, ids).last(<span class="hljs-string">&quot;ORDER BY FIELD(id,&quot;</span> + idStr + <span class="hljs-string">&quot;)&quot;</span>).list()<br>            .stream()<br>            .map(user -&gt; BeanUtil.copyProperties(user, UserDTO.class))<br>            .collect(Collectors.toList());<br>    <span class="hljs-comment">// 4.返回</span><br>    <span class="hljs-keyword">return</span> Result.ok(userDTOS);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="9、好友关注"><a href="#9、好友关注" class="headerlink" title="9、好友关注"></a>9、好友关注</h2><h3 id="9-1-好友关注-关注和取消关注"><a href="#9-1-好友关注-关注和取消关注" class="headerlink" title="9.1 好友关注-关注和取消关注"></a>9.1 好友关注-关注和取消关注</h3><p>针对用户的操作：可以对用户进行关注和取消关注功能。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302105.png" srcset="/img/loading.gif" lazyload alt="1653806140822"></p>
<p>实现思路：</p>
<p>需求：基于该表数据结构，实现两个接口：</p>
<ul>
<li>关注和取关接口</li>
<li>判断是否关注的接口</li>
</ul>
<p>关注是User之间的关系，是博主与粉丝的关系，数据库中有一张tb_follow表来标示：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302106.png" srcset="/img/loading.gif" lazyload alt="1653806253817"></p>
<p>注意: 这里需要把主键修改为自增长，简化开发。</p>
<p>FollowController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//关注</span><br><span class="hljs-meta">@PutMapping(&quot;/&#123;id&#125;/&#123;isFollow&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">follow</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> Long followUserId, <span class="hljs-meta">@PathVariable(&quot;isFollow&quot;)</span> Boolean isFollow)</span> &#123;<br>    <span class="hljs-keyword">return</span> followService.follow(followUserId, isFollow);<br>&#125;<br><span class="hljs-comment">//取消关注</span><br><span class="hljs-meta">@GetMapping(&quot;/or/not/&#123;id&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">isFollow</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> Long followUserId)</span> &#123;<br>      <span class="hljs-keyword">return</span> followService.isFollow(followUserId);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>FollowService</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//取消关注service</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">isFollow</span><span class="hljs-params">(Long followUserId)</span> &#123;<br>    <span class="hljs-comment">// 1.获取登录用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-comment">// 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?</span><br>    <span class="hljs-type">Integer</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> query().eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;follow_user_id&quot;</span>, followUserId).count();<br>    <span class="hljs-comment">// 3.判断</span><br>    <span class="hljs-keyword">return</span> Result.ok(count &gt; <span class="hljs-number">0</span>);<br>&#125;<br><br><span class="hljs-comment">//关注service</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">follow</span><span class="hljs-params">(Long followUserId, Boolean isFollow)</span> &#123;<br>    <span class="hljs-comment">// 1.获取登录用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;follows:&quot;</span> + userId;<br>    <span class="hljs-comment">// 1.判断到底是关注还是取关</span><br>    <span class="hljs-keyword">if</span> (isFollow) &#123;<br>        <span class="hljs-comment">// 2.关注，新增数据</span><br>        <span class="hljs-type">Follow</span> <span class="hljs-variable">follow</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Follow</span>();<br>        follow.setUserId(userId);<br>        follow.setFollowUserId(followUserId);<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> save(follow);<br><br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-comment">// 3.取关，删除 delete from tb_follow where user_id = ? and follow_user_id = ?</span><br>        remove(<span class="hljs-keyword">new</span> <span class="hljs-title class_">QueryWrapper</span>&lt;Follow&gt;()<br>               .eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;follow_user_id&quot;</span>, followUserId));<br><br>    &#125;<br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="9-2-好友关注-共同关注"><a href="#9-2-好友关注-共同关注" class="headerlink" title="9.2 好友关注-共同关注"></a>9.2 好友关注-共同关注</h3><p>想要去看共同关注的好友，需要首先进入到这个页面，这个页面会发起两个请求</p>
<p>1、去查询用户的详情</p>
<p>2、去查询用户的笔记</p>
<p>以上两个功能和共同关注没有什么关系，大家可以自行将笔记中的代码拷贝到idea中就可以实现这两个功能了，我们的重点在于共同关注功能。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302107.png" srcset="/img/loading.gif" lazyload alt="1653806706296"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// UserController 根据id查询用户</span><br><span class="hljs-meta">@GetMapping(&quot;/&#123;id&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryUserById</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> Long userId)</span>&#123;<br>    <span class="hljs-comment">// 查询详情</span><br>    <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> userService.getById(userId);<br>    <span class="hljs-keyword">if</span> (user == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-keyword">return</span> Result.ok();<br>    &#125;<br>    <span class="hljs-type">UserDTO</span> <span class="hljs-variable">userDTO</span> <span class="hljs-operator">=</span> BeanUtil.copyProperties(user, UserDTO.class);<br>    <span class="hljs-comment">// 返回</span><br>    <span class="hljs-keyword">return</span> Result.ok(userDTO);<br>&#125;<br><br><span class="hljs-comment">// BlogController  根据id查询博主的探店笔记</span><br><span class="hljs-meta">@GetMapping(&quot;/of/user&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogByUserId</span><span class="hljs-params">(</span><br><span class="hljs-params">    <span class="hljs-meta">@RequestParam(value = &quot;current&quot;, defaultValue = &quot;1&quot;)</span> Integer current,</span><br><span class="hljs-params">    <span class="hljs-meta">@RequestParam(&quot;id&quot;)</span> Long id)</span> &#123;<br>    <span class="hljs-comment">// 根据用户查询</span><br>    Page&lt;Blog&gt; page = blogService.query()<br>        .eq(<span class="hljs-string">&quot;user_id&quot;</span>, id).page(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Page</span>&lt;&gt;(current, SystemConstants.MAX_PAGE_SIZE));<br>    <span class="hljs-comment">// 获取当前页数据</span><br>    List&lt;Blog&gt; records = page.getRecords();<br>    <span class="hljs-keyword">return</span> Result.ok(records);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>接下来我们来看看共同关注如何实现：</p>
<p>需求：利用Redis中恰当的数据结构，实现共同关注功能。在博主个人页面展示出当前用户与博主的共同关注呢。</p>
<p>当然是使用我们之前学习过的set集合咯，在set集合中，有交集并集补集的api，我们可以把两人的关注的人分别放入到一个set集合中，然后再通过api去查看这两个set集合中的交集数据。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302108.png" srcset="/img/loading.gif" lazyload alt="1653806973212"></p>
<p>我们先来改造当前的关注列表</p>
<p>改造原因是因为我们需要在用户关注了某位用户后，需要将数据放入到set集合中，方便后续进行共同关注，同时当取消关注时，也需要从set集合中进行删除</p>
<p>FollowServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">follow</span><span class="hljs-params">(Long followUserId, Boolean isFollow)</span> &#123;<br>    <span class="hljs-comment">// 1.获取登录用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;follows:&quot;</span> + userId;<br>    <span class="hljs-comment">// 1.判断到底是关注还是取关</span><br>    <span class="hljs-keyword">if</span> (isFollow) &#123;<br>        <span class="hljs-comment">// 2.关注，新增数据</span><br>        <span class="hljs-type">Follow</span> <span class="hljs-variable">follow</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Follow</span>();<br>        follow.setUserId(userId);<br>        follow.setFollowUserId(followUserId);<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> save(follow);<br>        <span class="hljs-keyword">if</span> (isSuccess) &#123;<br>            <span class="hljs-comment">// 把关注用户的id，放入redis的set集合 sadd userId followerUserId</span><br>            stringRedisTemplate.opsForSet().add(key, followUserId.toString());<br>        &#125;<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-comment">// 3.取关，删除 delete from tb_follow where user_id = ? and follow_user_id = ?</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> remove(<span class="hljs-keyword">new</span> <span class="hljs-title class_">QueryWrapper</span>&lt;Follow&gt;()<br>                .eq(<span class="hljs-string">&quot;user_id&quot;</span>, userId).eq(<span class="hljs-string">&quot;follow_user_id&quot;</span>, followUserId));<br>        <span class="hljs-keyword">if</span> (isSuccess) &#123;<br>            <span class="hljs-comment">// 把关注用户的id从Redis集合中移除</span><br>            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>具体的关注代码：</strong></p>
<p>FollowServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">followCommons</span><span class="hljs-params">(Long id)</span> &#123;<br>    <span class="hljs-comment">// 1.获取当前用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;follows:&quot;</span> + userId;<br>    <span class="hljs-comment">// 2.求交集</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">key2</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;follows:&quot;</span> + id;<br>    Set&lt;String&gt; intersect = stringRedisTemplate.opsForSet().intersect(key, key2);<br>    <span class="hljs-keyword">if</span> (intersect == <span class="hljs-literal">null</span> || intersect.isEmpty()) &#123;<br>        <span class="hljs-comment">// 无交集</span><br>        <span class="hljs-keyword">return</span> Result.ok(Collections.emptyList());<br>    &#125;<br>    <span class="hljs-comment">// 3.解析id集合</span><br>    List&lt;Long&gt; ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());<br>    <span class="hljs-comment">// 4.查询用户</span><br>    List&lt;UserDTO&gt; users = userService.listByIds(ids)<br>            .stream()<br>            .map(user -&gt; BeanUtil.copyProperties(user, UserDTO.class))<br>            .collect(Collectors.toList());<br>    <span class="hljs-keyword">return</span> Result.ok(users);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="9-3-好友关注-Feed流实现方案"><a href="#9-3-好友关注-Feed流实现方案" class="headerlink" title="9.3 好友关注-Feed流实现方案"></a>9.3 好友关注-Feed流实现方案</h3><p>当我们关注了用户后，这个用户发了动态，那么我们应该把这些数据推送给用户，这个需求，其实我们又把他叫做Feed流，关注推送也叫做Feed流，直译为投喂。为用户持续的提供“沉浸式”的体验，通过无限下拉刷新获取新的信息。</p>
<p>对于传统的模式的内容解锁：我们是需要用户去通过搜索引擎或者是其他的方式去解锁想要看的内容</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302109.png" srcset="/img/loading.gif" lazyload alt="1653808641260"></p>
<p>对于新型的Feed流的的效果：不需要我们用户再去推送信息，而是系统分析用户到底想要什么，然后直接把内容推送给用户，从而使用户能够更加的节约时间，不用主动去寻找。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302110.png" srcset="/img/loading.gif" lazyload alt="1653808993693"></p>
<p>Feed流的实现有两种模式：</p>
<p>Feed流产品有两种常见模式：<br>Timeline：不做内容筛选，简单的按照内容发布时间排序，常用于好友或关注。例如朋友圈</p>
<ul>
<li>优点：信息全面，不会有缺失。并且实现也相对简单</li>
<li>缺点：信息噪音较多，用户不一定感兴趣，内容获取效率低</li>
</ul>
<p>智能排序：利用智能算法屏蔽掉违规的、用户不感兴趣的内容。推送用户感兴趣信息来吸引用户</p>
<ul>
<li><p>优点：投喂用户感兴趣信息，用户粘度很高，容易沉迷</p>
</li>
<li><p>缺点：如果算法不精准，可能起到反作用<br>本例中的个人页面，是基于关注的好友来做Feed流，只需要拿到我们关注用户的信息，然后按照时间排序即可，因此采用Timeline的模式。该模式的实现方案有三种：</p>
</li>
<li><p>拉模式</p>
</li>
<li><p>推模式</p>
</li>
<li><p>推拉结合</p>
</li>
</ul>
<p><strong>拉模式</strong>：也叫做读扩散</p>
<p>该模式的核心含义就是：当张三和李四和王五发了消息后，都会保存在自己的写邮箱中，假设赵六要读取信息，那么他会从读取他自己的收件箱，此时系统会从他关注的人群中，把他关注人写全部都进行拉取，然后在进行排序</p>
<p>优点：比较节约空间，因为赵六在读信息时，并没有重复读取，而且读取完之后可以把他的收件箱进行清除。</p>
<p>缺点：比较延迟，当用户读取数据时才去关注的人里边去读取数据，假设用户关注了大量的用户，那么此时就会拉取海量的内容，对服务器压力巨大。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302111.png" srcset="/img/loading.gif" lazyload alt="1653809450816"></p>
<p><strong>推模式</strong>：也叫做写扩散。</p>
<p>推模式是没有写邮箱的，当张三写了一个内容，此时会主动的把张三写的内容发送到他的粉丝收件箱中去，假设此时李四再来读取，就不用再去临时拉取了</p>
<p>优点：时效快，不用临时拉取</p>
<p>缺点：内存压力大，假设一个大V写信息，很多人关注他， 就会写很多分数据到粉丝那边去</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302112.png" srcset="/img/loading.gif" lazyload alt="1653809875208"></p>
<p><strong>推拉结合模式</strong>：也叫做读写混合，兼具推和拉两种模式的优点。</p>
<p>推拉模式是一个折中的方案，站在发件人这一段，如果是个普通的人，那么我们采用写扩散的方式，直接把数据写入到他的粉丝中去，因为普通的人他的粉丝关注量比较小，所以这样做没有压力，如果是大V，那么他是直接将数据先写入到一份到发件箱里边去，然后再直接写一份到活跃粉丝收件箱里边去，现在站在收件人这端来看，如果是活跃粉丝，那么大V和普通的人发的都会直接写入到自己收件箱里边来，而如果是普通的粉丝，由于他们上线不是很频繁，所以等他们上线时，再从发件箱里边去拉信息。</p>
<h3 id="9-4-好友关注-推送到粉丝收件箱"><a href="#9-4-好友关注-推送到粉丝收件箱" class="headerlink" title="9.4 好友关注-推送到粉丝收件箱"></a>9.4 好友关注-推送到粉丝收件箱</h3><p>需求：</p>
<ul>
<li>修改新增探店笔记的业务，在保存blog到数据库的同时，推送到粉丝的收件箱</li>
<li>收件箱满足可以根据时间戳排序，必须用Redis的数据结构实现</li>
<li>查询收件箱数据时，可以实现分页查询</li>
</ul>
<p>Feed流中的数据会不断更新，所以数据的角标也在变化，因此不能采用传统的分页模式。</p>
<p>传统了分页在feed流是不适用的，因为我们的数据会随时发生变化</p>
<p>假设在t1 时刻，我们去读取第一页，此时page &#x3D; 1 ，size &#x3D; 5 ，那么我们拿到的就是10<del>6 这几条记录，假设现在t2时候又发布了一条记录，此时t3 时刻，我们来读取第二页，读取第二页传入的参数是page&#x3D;2 ，size&#x3D;5 ，那么此时读取到的第二页实际上是从6 开始，然后是6</del>2 ，那么我们就读取到了重复的数据，所以feed流的分页，不能采用原始方案来做。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302114.png" srcset="/img/loading.gif" lazyload alt="1653813047671"></p>
<p>Feed流的滚动分页</p>
<p>我们需要记录每次操作的最后一条，然后从这个位置开始去读取数据</p>
<p>举个例子：我们从t1时刻开始，拿第一页数据，拿到了10~6，然后记录下当前最后一次拿取的记录，就是6，t2时刻发布了新的记录，此时这个11放到最顶上，但是不会影响我们之前记录的6，此时t3时刻来拿第二页，第二页这个时候拿数据，还是从6后一点的5去拿，就拿到了5-1的记录。我们这个地方可以采用sortedSet来做，可以进行范围查询，并且还可以记录当前获取数据时间戳最小值，就可以实现滚动分页了</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302116.png" srcset="/img/loading.gif" lazyload alt="1653813462834"></p>
<p>核心的意思：就是我们在保存完探店笔记后，获得到当前笔记的粉丝，然后把数据推送到粉丝的redis中去。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">saveBlog</span><span class="hljs-params">(Blog blog)</span> &#123;<br>    <span class="hljs-comment">// 1.获取登录用户</span><br>    <span class="hljs-type">UserDTO</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> UserHolder.getUser();<br>    blog.setUserId(user.getId());<br>    <span class="hljs-comment">// 2.保存探店笔记</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">isSuccess</span> <span class="hljs-operator">=</span> save(blog);<br>    <span class="hljs-keyword">if</span>(!isSuccess)&#123;<br>        <span class="hljs-keyword">return</span> Result.fail(<span class="hljs-string">&quot;新增笔记失败!&quot;</span>);<br>    &#125;<br>    <span class="hljs-comment">// 3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?</span><br>    List&lt;Follow&gt; follows = followService.query().eq(<span class="hljs-string">&quot;follow_user_id&quot;</span>, user.getId()).list();<br>    <span class="hljs-comment">// 4.推送笔记id给所有粉丝</span><br>    <span class="hljs-keyword">for</span> (Follow follow : follows) &#123;<br>        <span class="hljs-comment">// 4.1.获取粉丝id</span><br>        <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> follow.getUserId();<br>        <span class="hljs-comment">// 4.2.推送</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> FEED_KEY + userId;<br>        stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());<br>    &#125;<br>    <span class="hljs-comment">// 5.返回id</span><br>    <span class="hljs-keyword">return</span> Result.ok(blog.getId());<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="9-5好友关注-实现分页查询收邮箱"><a href="#9-5好友关注-实现分页查询收邮箱" class="headerlink" title="9.5好友关注-实现分页查询收邮箱"></a>9.5好友关注-实现分页查询收邮箱</h3><p>需求：在个人主页的“关注”卡片中，查询并展示推送的Blog信息：</p>
<p>具体操作如下：</p>
<p>1、每次查询完成后，我们要分析出查询出数据的最小时间戳，这个值会作为下一次查询的条件</p>
<p>2、我们需要找到与上一次查询相同的查询个数作为偏移量，下次查询时，跳过这些查询过的数据，拿到我们需要的数据</p>
<p>综上：我们的请求参数中就需要携带 lastId：上一次查询的最小时间戳 和偏移量这两个参数。</p>
<p>这两个参数第一次会由前端来指定，以后的查询就根据后台结果作为条件，再次传递到后台。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302117.png" srcset="/img/loading.gif" lazyload alt="1653819821591"></p>
<p>一、定义出来具体的返回值实体类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ScrollResult</span> &#123;<br>    <span class="hljs-keyword">private</span> List&lt;?&gt; list;<br>    <span class="hljs-keyword">private</span> Long minTime;<br>    <span class="hljs-keyword">private</span> Integer offset;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>BlogController</p>
<p>注意：RequestParam 表示接受url地址栏传参的注解，当方法上参数的名称和url地址栏不相同时，可以通过RequestParam 来进行指定</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/of/follow&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogOfFollow</span><span class="hljs-params">(</span><br><span class="hljs-params">    <span class="hljs-meta">@RequestParam(&quot;lastId&quot;)</span> Long max, <span class="hljs-meta">@RequestParam(value = &quot;offset&quot;, defaultValue = &quot;0&quot;)</span> Integer offset)</span>&#123;<br>    <span class="hljs-keyword">return</span> blogService.queryBlogOfFollow(max, offset);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>BlogServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryBlogOfFollow</span><span class="hljs-params">(Long max, Integer offset)</span> &#123;<br>    <span class="hljs-comment">// 1.获取当前用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-comment">// 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> FEED_KEY + userId;<br>    Set&lt;ZSetOperations.TypedTuple&lt;String&gt;&gt; typedTuples = stringRedisTemplate.opsForZSet()<br>        .reverseRangeByScoreWithScores(key, <span class="hljs-number">0</span>, max, offset, <span class="hljs-number">2</span>);<br>    <span class="hljs-comment">// 3.非空判断</span><br>    <span class="hljs-keyword">if</span> (typedTuples == <span class="hljs-literal">null</span> || typedTuples.isEmpty()) &#123;<br>        <span class="hljs-keyword">return</span> Result.ok();<br>    &#125;<br>    <span class="hljs-comment">// 4.解析数据：blogId、minTime（时间戳）、offset</span><br>    List&lt;Long&gt; ids = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;(typedTuples.size());<br>    <span class="hljs-type">long</span> <span class="hljs-variable">minTime</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; <span class="hljs-comment">// 2</span><br>    <span class="hljs-type">int</span> <span class="hljs-variable">os</span> <span class="hljs-operator">=</span> <span class="hljs-number">1</span>; <span class="hljs-comment">// 2</span><br>    <span class="hljs-keyword">for</span> (ZSetOperations.TypedTuple&lt;String&gt; tuple : typedTuples) &#123; <span class="hljs-comment">// 5 4 4 2 2</span><br>        <span class="hljs-comment">// 4.1.获取id</span><br>        ids.add(Long.valueOf(tuple.getValue()));<br>        <span class="hljs-comment">// 4.2.获取分数(时间戳）</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">time</span> <span class="hljs-operator">=</span> tuple.getScore().longValue();<br>        <span class="hljs-keyword">if</span>(time == minTime)&#123;<br>            os++;<br>        &#125;<span class="hljs-keyword">else</span>&#123;<br>            minTime = time;<br>            os = <span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;<br>	os = minTime == max ? os : os + offset;<br>    <span class="hljs-comment">// 5.根据id查询blog</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">idStr</span> <span class="hljs-operator">=</span> StrUtil.join(<span class="hljs-string">&quot;,&quot;</span>, ids);<br>    List&lt;Blog&gt; blogs = query().in(<span class="hljs-string">&quot;id&quot;</span>, ids).last(<span class="hljs-string">&quot;ORDER BY FIELD(id,&quot;</span> + idStr + <span class="hljs-string">&quot;)&quot;</span>).list();<br><br>    <span class="hljs-keyword">for</span> (Blog blog : blogs) &#123;<br>        <span class="hljs-comment">// 5.1.查询blog有关的用户</span><br>        queryBlogUser(blog);<br>        <span class="hljs-comment">// 5.2.查询blog是否被点赞</span><br>        isBlogLiked(blog);<br>    &#125;<br><br>    <span class="hljs-comment">// 6.封装并返回</span><br>    <span class="hljs-type">ScrollResult</span> <span class="hljs-variable">r</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ScrollResult</span>();<br>    r.setList(blogs);<br>    r.setOffset(os);<br>    r.setMinTime(minTime);<br><br>    <span class="hljs-keyword">return</span> Result.ok(r);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="10、附近商户"><a href="#10、附近商户" class="headerlink" title="10、附近商户"></a>10、附近商户</h2><h3 id="10-1、附近商户-GEO数据结构的基本用法"><a href="#10-1、附近商户-GEO数据结构的基本用法" class="headerlink" title="10.1、附近商户-GEO数据结构的基本用法"></a>10.1、附近商户-GEO数据结构的基本用法</h3><p>GEO就是Geolocation的简写形式，代表地理坐标。Redis在3.2版本中加入了对GEO的支持，允许存储地理坐标信息，帮助我们根据经纬度来检索数据。常见的命令有：</p>
<ul>
<li>GEOADD：添加一个地理空间信息，包含：经度（longitude）、纬度（latitude）、值（member）</li>
<li>GEODIST：计算指定的两个点之间的距离并返回</li>
<li>GEOHASH：将指定member的坐标转为hash字符串形式并返回</li>
<li>GEOPOS：返回指定member的坐标</li>
<li>GEORADIUS：指定圆心、半径，找到该圆内包含的所有member，并按照与圆心之间的距离排序后返回。6.以后已废弃</li>
<li>GEOSEARCH：在指定范围内搜索member，并按照与指定点之间的距离排序后返回。范围可以是圆形或矩形。6.2.新功能</li>
<li>GEOSEARCHSTORE：与GEOSEARCH功能一致，不过可以把结果存储到一个指定的key。 6.2.新功能</li>
</ul>
<h3 id="10-2、-附近商户-导入店铺数据到GEO"><a href="#10-2、-附近商户-导入店铺数据到GEO" class="headerlink" title="10.2、 附近商户-导入店铺数据到GEO"></a>10.2、 附近商户-导入店铺数据到GEO</h3><p>具体场景说明：</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302118.png" srcset="/img/loading.gif" lazyload alt="1653822036941"></p>
<p>当我们点击美食之后，会出现一系列的商家，商家中可以按照多种排序方式，我们此时关注的是距离，这个地方就需要使用到我们的GEO，向后台传入当前app收集的地址(我们此处是写死的) ，以当前坐标作为圆心，同时绑定相同的店家类型type，以及分页信息，把这几个条件传入后台，后台查询出对应的数据再返回。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302119.png" srcset="/img/loading.gif" lazyload alt="1653822021827"></p>
<p>我们要做的事情是：将数据库表中的数据导入到redis中去，redis中的GEO，GEO在redis中就一个menber和一个经纬度，我们把x和y轴传入到redis做的经纬度位置去，但我们不能把所有的数据都放入到menber中去，毕竟作为redis是一个内存级数据库，如果存海量数据，redis还是力不从心，所以我们在这个地方存储他的id即可。</p>
<p>但是这个时候还有一个问题，就是在redis中并没有存储type，所以我们无法根据type来对数据进行筛选，所以我们可以按照商户类型做分组，类型相同的商户作为同一组，以typeId为key存入同一个GEO集合中即可</p>
<p>代码</p>
<p>HmDianPingApplicationTests</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">void</span> <span class="hljs-title function_">loadShopData</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 1.查询店铺信息</span><br>    List&lt;Shop&gt; list = shopService.list();<br>    <span class="hljs-comment">// 2.把店铺分组，按照typeId分组，typeId一致的放到一个集合</span><br>    Map&lt;Long, List&lt;Shop&gt;&gt; map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));<br>    <span class="hljs-comment">// 3.分批完成写入Redis</span><br>    <span class="hljs-keyword">for</span> (Map.Entry&lt;Long, List&lt;Shop&gt;&gt; entry : map.entrySet()) &#123;<br>        <span class="hljs-comment">// 3.1.获取类型id</span><br>        <span class="hljs-type">Long</span> <span class="hljs-variable">typeId</span> <span class="hljs-operator">=</span> entry.getKey();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> SHOP_GEO_KEY + typeId;<br>        <span class="hljs-comment">// 3.2.获取同类型的店铺的集合</span><br>        List&lt;Shop&gt; value = entry.getValue();<br>        List&lt;RedisGeoCommands.GeoLocation&lt;String&gt;&gt; locations = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;(value.size());<br>        <span class="hljs-comment">// 3.3.写入redis GEOADD key 经度 纬度 member</span><br>        <span class="hljs-keyword">for</span> (Shop shop : value) &#123;<br>            <span class="hljs-comment">// stringRedisTemplate.opsForGeo().add(key, new Point(shop.getX(), shop.getY()), shop.getId().toString());</span><br>            locations.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RedisGeoCommands</span>.GeoLocation&lt;&gt;(<br>                    shop.getId().toString(),<br>                    <span class="hljs-keyword">new</span> <span class="hljs-title class_">Point</span>(shop.getX(), shop.getY())<br>            ));<br>        &#125;<br>        stringRedisTemplate.opsForGeo().add(key, locations);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="10-3-附近商户-实现附近商户功能"><a href="#10-3-附近商户-实现附近商户功能" class="headerlink" title="10.3 附近商户-实现附近商户功能"></a>10.3 附近商户-实现附近商户功能</h3><p>SpringDataRedis的2.3.9版本并不支持Redis 6.2提供的GEOSEARCH命令，因此我们需要提示其版本，修改自己的POM</p>
<p>第一步：导入pom</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>    &lt;exclusions&gt;<br>        &lt;exclusion&gt;<br>            &lt;artifactId&gt;spring-data-redis&lt;/artifactId&gt;<br>            &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;<br>        &lt;/exclusion&gt;<br>        &lt;exclusion&gt;<br>            &lt;artifactId&gt;lettuce-core&lt;/artifactId&gt;<br>            &lt;groupId&gt;io.lettuce&lt;/groupId&gt;<br>        &lt;/exclusion&gt;<br>    &lt;/exclusions&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-data-redis&lt;/artifactId&gt;<br>    &lt;version&gt;<span class="hljs-number">2.6</span><span class="hljs-number">.2</span>&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.lettuce&lt;/groupId&gt;<br>    &lt;artifactId&gt;lettuce-core&lt;/artifactId&gt;<br>    &lt;version&gt;<span class="hljs-number">6.1</span><span class="hljs-number">.6</span>.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;<br></code></pre></td></tr></table></figure>

<p>第二步：</p>
<p>ShopController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/of/type&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryShopByType</span><span class="hljs-params">(</span><br><span class="hljs-params">        <span class="hljs-meta">@RequestParam(&quot;typeId&quot;)</span> Integer typeId,</span><br><span class="hljs-params">        <span class="hljs-meta">@RequestParam(value = &quot;current&quot;, defaultValue = &quot;1&quot;)</span> Integer current,</span><br><span class="hljs-params">        <span class="hljs-meta">@RequestParam(value = &quot;x&quot;, required = false)</span> Double x,</span><br><span class="hljs-params">        <span class="hljs-meta">@RequestParam(value = &quot;y&quot;, required = false)</span> Double y</span><br><span class="hljs-params">)</span> &#123;<br>   <span class="hljs-keyword">return</span> shopService.queryShopByType(typeId, current, x, y);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>ShopServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Result <span class="hljs-title function_">queryShopByType</span><span class="hljs-params">(Integer typeId, Integer current, Double x, Double y)</span> &#123;<br>        <span class="hljs-comment">// 1.判断是否需要根据坐标查询</span><br>        <span class="hljs-keyword">if</span> (x == <span class="hljs-literal">null</span> || y == <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-comment">// 不需要坐标查询，按数据库查询</span><br>            Page&lt;Shop&gt; page = query()<br>                    .eq(<span class="hljs-string">&quot;type_id&quot;</span>, typeId)<br>                    .page(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Page</span>&lt;&gt;(current, SystemConstants.DEFAULT_PAGE_SIZE));<br>            <span class="hljs-comment">// 返回数据</span><br>            <span class="hljs-keyword">return</span> Result.ok(page.getRecords());<br>        &#125;<br><br>        <span class="hljs-comment">// 2.计算分页参数</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">from</span> <span class="hljs-operator">=</span> (current - <span class="hljs-number">1</span>) * SystemConstants.DEFAULT_PAGE_SIZE;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">end</span> <span class="hljs-operator">=</span> current * SystemConstants.DEFAULT_PAGE_SIZE;<br><br>        <span class="hljs-comment">// 3.查询redis、按照距离排序、分页。结果：shopId、distance</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> SHOP_GEO_KEY + typeId;<br>        GeoResults&lt;RedisGeoCommands.GeoLocation&lt;String&gt;&gt; results = stringRedisTemplate.opsForGeo() <span class="hljs-comment">// GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE</span><br>                .search(<br>                        key,<br>                        GeoReference.fromCoordinate(x, y),<br>                        <span class="hljs-keyword">new</span> <span class="hljs-title class_">Distance</span>(<span class="hljs-number">5000</span>),<br>                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)<br>                );<br>        <span class="hljs-comment">// 4.解析出id</span><br>        <span class="hljs-keyword">if</span> (results == <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-keyword">return</span> Result.ok(Collections.emptyList());<br>        &#125;<br>        List&lt;GeoResult&lt;RedisGeoCommands.GeoLocation&lt;String&gt;&gt;&gt; list = results.getContent();<br>        <span class="hljs-keyword">if</span> (list.size() &lt;= from) &#123;<br>            <span class="hljs-comment">// 没有下一页了，结束</span><br>            <span class="hljs-keyword">return</span> Result.ok(Collections.emptyList());<br>        &#125;<br>        <span class="hljs-comment">// 4.1.截取 from ~ end的部分</span><br>        List&lt;Long&gt; ids = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;(list.size());<br>        Map&lt;String, Distance&gt; distanceMap = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;(list.size());<br>        list.stream().skip(from).forEach(result -&gt; &#123;<br>            <span class="hljs-comment">// 4.2.获取店铺id</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">shopIdStr</span> <span class="hljs-operator">=</span> result.getContent().getName();<br>            ids.add(Long.valueOf(shopIdStr));<br>            <span class="hljs-comment">// 4.3.获取距离</span><br>            <span class="hljs-type">Distance</span> <span class="hljs-variable">distance</span> <span class="hljs-operator">=</span> result.getDistance();<br>            distanceMap.put(shopIdStr, distance);<br>        &#125;);<br>        <span class="hljs-comment">// 5.根据id查询Shop</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">idStr</span> <span class="hljs-operator">=</span> StrUtil.join(<span class="hljs-string">&quot;,&quot;</span>, ids);<br>        List&lt;Shop&gt; shops = query().in(<span class="hljs-string">&quot;id&quot;</span>, ids).last(<span class="hljs-string">&quot;ORDER BY FIELD(id,&quot;</span> + idStr + <span class="hljs-string">&quot;)&quot;</span>).list();<br>        <span class="hljs-keyword">for</span> (Shop shop : shops) &#123;<br>            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());<br>        &#125;<br>        <span class="hljs-comment">// 6.返回</span><br>        <span class="hljs-keyword">return</span> Result.ok(shops);<br>    &#125;<br></code></pre></td></tr></table></figure>



<h2 id="11、用户签到"><a href="#11、用户签到" class="headerlink" title="11、用户签到"></a>11、用户签到</h2><h4 id="11-1、用户签到-BitMap功能演示"><a href="#11-1、用户签到-BitMap功能演示" class="headerlink" title="11.1、用户签到-BitMap功能演示"></a>11.1、用户签到-BitMap功能演示</h4><p>我们针对签到功能完全可以通过mysql来完成，比如说以下这张表</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302120.png" srcset="/img/loading.gif" lazyload alt="1653823145495"></p>
<p>用户一次签到，就是一条记录，假如有1000万用户，平均每人每年签到次数为10次，则这张表一年的数据量为 1亿条</p>
<p>每签到一次需要使用（8 + 8 + 1 + 1 + 3 + 1）共22 字节的内存，一个月则最多需要600多字节</p>
<p>我们如何能够简化一点呢？其实可以考虑小时候一个挺常见的方案，就是小时候，咱们准备一张小小的卡片，你只要签到就打上一个勾，我最后判断你是否签到，其实只需要到小卡片上看一看就知道了</p>
<p>我们可以采用类似这样的方案来实现我们的签到需求。</p>
<p>我们按月来统计用户签到信息，签到记录为1，未签到则记录为0.</p>
<p>把每一个bit位对应当月的每一天，形成了映射关系。用0和1标示业务状态，这种思路就称为位图（BitMap）。这样我们就用极小的空间，来实现了大量数据的表示</p>
<p>Redis中是利用string类型数据结构实现BitMap，因此最大上限是512M，转换为bit则是 2^32个bit位。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302121.png" srcset="/img/loading.gif" lazyload alt="1653824498278"></p>
<p>BitMap的操作命令有：</p>
<ul>
<li>SETBIT：向指定位置（offset）存入一个0或1</li>
<li>GETBIT ：获取指定位置（offset）的bit值</li>
<li>BITCOUNT ：统计BitMap中值为1的bit位的数量</li>
<li>BITFIELD ：操作（查询、修改、自增）BitMap中bit数组中的指定位置（offset）的值</li>
<li>BITFIELD_RO ：获取BitMap中bit数组，并以十进制形式返回</li>
<li>BITOP ：将多个BitMap的结果做位运算（与 、或、异或）</li>
<li>BITPOS ：查找bit数组中指定范围内第一个0或1出现的位置</li>
</ul>
<h4 id="11-2-、用户签到-实现签到功能"><a href="#11-2-、用户签到-实现签到功能" class="headerlink" title="11.2 、用户签到-实现签到功能"></a>11.2 、用户签到-实现签到功能</h4><p>需求：实现签到接口，将当前用户当天签到信息保存到Redis中</p>
<p>思路：我们可以把年和月作为bitMap的key，然后保存到一个bitMap中，每次签到就到对应的位上把数字从0变成1，只要对应是1，就表明说明这一天已经签到了，反之则没有签到。</p>
<p>我们通过接口文档发现，此接口并没有传递任何的参数，没有参数怎么确实是哪一天签到呢？这个很容易，可以通过后台代码直接获取即可，然后到对应的地址上去修改bitMap。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302122.png" srcset="/img/loading.gif" lazyload alt="1653833970361"></p>
<p><strong>代码</strong></p>
<p>UserController</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/sign&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">sign</span><span class="hljs-params">()</span>&#123;<br>   <span class="hljs-keyword">return</span> userService.sign();<br>&#125;<br></code></pre></td></tr></table></figure>

<p>UserServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">sign</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 1.获取当前登录用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-comment">// 2.获取日期</span><br>    <span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">now</span> <span class="hljs-operator">=</span> LocalDateTime.now();<br>    <span class="hljs-comment">// 3.拼接key</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">keySuffix</span> <span class="hljs-operator">=</span> now.format(DateTimeFormatter.ofPattern(<span class="hljs-string">&quot;:yyyyMM&quot;</span>));<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> USER_SIGN_KEY + userId + keySuffix;<br>    <span class="hljs-comment">// 4.获取今天是本月的第几天</span><br>    <span class="hljs-type">int</span> <span class="hljs-variable">dayOfMonth</span> <span class="hljs-operator">=</span> now.getDayOfMonth();<br>    <span class="hljs-comment">// 5.写入Redis SETBIT key offset 1</span><br>    stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - <span class="hljs-number">1</span>, <span class="hljs-literal">true</span>);<br>    <span class="hljs-keyword">return</span> Result.ok();<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="11-3-用户签到-签到统计"><a href="#11-3-用户签到-签到统计" class="headerlink" title="11.3 用户签到-签到统计"></a>11.3 用户签到-签到统计</h4><p><strong>问题1：</strong>什么叫做连续签到天数？<br>从最后一次签到开始向前统计，直到遇到第一次未签到为止，计算总的签到次数，就是连续签到天数。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302123.png" srcset="/img/loading.gif" lazyload alt="1653834455899"></p>
<p>Java逻辑代码：获得当前这个月的最后一次签到数据，定义一个计数器，然后不停的向前统计，直到获得第一个非0的数字即可，每得到一个非0的数字计数器+1，直到遍历完所有的数据，就可以获得当前月的签到总天数了</p>
<p><strong>问题2：</strong>如何得到本月到今天为止的所有签到数据？</p>
<p>  BITFIELD key GET u[dayOfMonth] 0</p>
<p>假设今天是10号，那么我们就可以从当前月的第一天开始，获得到当前这一天的位数，是10号，那么就是10位，去拿这段时间的数据，就能拿到所有的数据了，那么这10天里边签到了多少次呢？统计有多少个1即可。</p>
<p><strong>问题3：如何从后向前遍历每个bit位？</strong></p>
<p>注意：bitMap返回的数据是10进制，哪假如说返回一个数字8，那么我哪儿知道到底哪些是0，哪些是1呢？我们只需要让得到的10进制数字和1做与运算就可以了，因为1只有遇见1 才是1，其他数字都是0 ，我们把签到结果和1进行与操作，每与一次，就把签到结果向右移动一位，依次内推，我们就能完成逐个遍历的效果了。</p>
<p>需求：实现下面接口，统计当前用户截止当前时间在本月的连续签到天数</p>
<p>有用户有时间我们就可以组织出对应的key，此时就能找到这个用户截止这天的所有签到记录，再根据这套算法，就能统计出来他连续签到的次数了</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302124.png" srcset="/img/loading.gif" lazyload alt="1653835784444"></p>
<p>代码</p>
<p><strong>UserController</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/sign/count&quot;)</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">signCount</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">return</span> userService.signCount();<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>UserServiceImpl</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">signCount</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 1.获取当前登录用户</span><br>    <span class="hljs-type">Long</span> <span class="hljs-variable">userId</span> <span class="hljs-operator">=</span> UserHolder.getUser().getId();<br>    <span class="hljs-comment">// 2.获取日期</span><br>    <span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">now</span> <span class="hljs-operator">=</span> LocalDateTime.now();<br>    <span class="hljs-comment">// 3.拼接key</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">keySuffix</span> <span class="hljs-operator">=</span> now.format(DateTimeFormatter.ofPattern(<span class="hljs-string">&quot;:yyyyMM&quot;</span>));<br>    <span class="hljs-type">String</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> USER_SIGN_KEY + userId + keySuffix;<br>    <span class="hljs-comment">// 4.获取今天是本月的第几天</span><br>    <span class="hljs-type">int</span> <span class="hljs-variable">dayOfMonth</span> <span class="hljs-operator">=</span> now.getDayOfMonth();<br>    <span class="hljs-comment">// 5.获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0</span><br>    List&lt;Long&gt; result = stringRedisTemplate.opsForValue().bitField(<br>            key,<br>            BitFieldSubCommands.create()<br>                    .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(<span class="hljs-number">0</span>)<br>    );<br>    <span class="hljs-keyword">if</span> (result == <span class="hljs-literal">null</span> || result.isEmpty()) &#123;<br>        <span class="hljs-comment">// 没有任何签到结果</span><br>        <span class="hljs-keyword">return</span> Result.ok(<span class="hljs-number">0</span>);<br>    &#125;<br>    <span class="hljs-type">Long</span> <span class="hljs-variable">num</span> <span class="hljs-operator">=</span> result.get(<span class="hljs-number">0</span>);<br>    <span class="hljs-keyword">if</span> (num == <span class="hljs-literal">null</span> || num == <span class="hljs-number">0</span>) &#123;<br>        <span class="hljs-keyword">return</span> Result.ok(<span class="hljs-number">0</span>);<br>    &#125;<br>    <span class="hljs-comment">// 6.循环遍历</span><br>    <span class="hljs-type">int</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>        <span class="hljs-comment">// 6.1.让这个数字与1做与运算，得到数字的最后一个bit位  // 判断这个bit位是否为0</span><br>        <span class="hljs-keyword">if</span> ((num &amp; <span class="hljs-number">1</span>) == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-comment">// 如果为0，说明未签到，结束</span><br>            <span class="hljs-keyword">break</span>;<br>        &#125;<span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-comment">// 如果不为0，说明已签到，计数器+1</span><br>            count++;<br>        &#125;<br>        <span class="hljs-comment">// 把数字右移一位，抛弃最后一个bit位，继续下一个bit位</span><br>        num &gt;&gt;&gt;= <span class="hljs-number">1</span>;<br>    &#125;<br>    <span class="hljs-keyword">return</span> Result.ok(count);<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="11-4-额外加餐-关于使用bitmap来解决缓存穿透的方案"><a href="#11-4-额外加餐-关于使用bitmap来解决缓存穿透的方案" class="headerlink" title="11.4 额外加餐-关于使用bitmap来解决缓存穿透的方案"></a>11.4 额外加餐-关于使用bitmap来解决缓存穿透的方案</h4><p>回顾<strong>缓存穿透</strong>：</p>
<p>发起了一个数据库不存在的，redis里边也不存在的数据，通常你可以把他看成一个攻击</p>
<p>解决方案：</p>
<ul>
<li><p>判断id&lt;0</p>
</li>
<li><p>如果数据库是空，那么就可以直接往redis里边把这个空数据缓存起来</p>
</li>
</ul>
<p>第一种解决方案：遇到的问题是如果用户访问的是id不存在的数据，则此时就无法生效</p>
<p>第二种解决方案：遇到的问题是：如果是不同的id那就可以防止下次过来直击数据</p>
<p>所以我们如何解决呢？</p>
<p>我们可以将数据库的数据，所对应的id写入到一个list集合中，当用户过来访问的时候，我们直接去判断list中是否包含当前的要查询的数据，如果说用户要查询的id数据并不在list集合中，则直接返回，如果list中包含对应查询的id数据，则说明不是一次缓存穿透数据，则直接放行。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302125.png" srcset="/img/loading.gif" lazyload alt="1653836416586"></p>
<p>现在的问题是这个主键其实并没有那么短，而是很长的一个 主键</p>
<p>哪怕你单独去提取这个主键，但是在11年左右，淘宝的商品总量就已经超过10亿个</p>
<p>所以如果采用以上方案，这个list也会很大，所以我们可以使用bitmap来减少list的存储空间</p>
<p>我们可以把list数据抽象成一个非常大的bitmap，我们不再使用list，而是将db中的id数据利用哈希思想，比如：</p>
<p>id % bitmap.size  &#x3D; 算出当前这个id对应应该落在bitmap的哪个索引上，然后将这个值从0变成1，然后当用户来查询数据时，此时已经没有了list，让用户用他查询的id去用相同的哈希算法， 算出来当前这个id应当落在bitmap的哪一位，然后判断这一位是0，还是1，如果是0则表明这一位上的数据一定不存在，  采用这种方式来处理，需要重点考虑一个事情，就是误差率，所谓的误差率就是指当发生哈希冲突的时候，产生的误差。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302126.png" srcset="/img/loading.gif" lazyload alt="1653836578970"></p>
<h2 id="12、UV统计"><a href="#12、UV统计" class="headerlink" title="12、UV统计"></a>12、UV统计</h2><h3 id="12-1-、UV统计-HyperLogLog"><a href="#12-1-、UV统计-HyperLogLog" class="headerlink" title="12.1 、UV统计-HyperLogLog"></a>12.1 、UV统计-HyperLogLog</h3><p>首先我们搞懂两个概念：</p>
<ul>
<li>UV：全称Unique Visitor，也叫独立访客量，是指通过互联网访问、浏览这个网页的自然人。1天内同一个用户多次访问该网站，只记录1次。</li>
<li>PV：全称Page View，也叫页面访问量或点击量，用户每访问网站的一个页面，记录1次PV，用户多次打开页面，则记录多次PV。往往用来衡量网站的流量。</li>
</ul>
<p>通常来说UV会比PV大很多，所以衡量同一个网站的访问量，我们需要综合考虑很多因素，所以我们只是单纯的把这两个值作为一个参考值</p>
<p>UV统计在服务端做会比较麻烦，因为要判断该用户是否已经统计过了，需要将统计过的用户信息保存。但是如果每个访问的用户都保存到Redis中，数据量会非常恐怖，那怎么处理呢？</p>
<p>Hyperloglog(HLL)是从Loglog算法派生的概率算法，用于确定非常大的集合的基数，而不需要存储其所有值。相关算法原理大家可以参考：<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903785744056333#heading-0">https://juejin.cn/post/6844903785744056333#heading-0</a><br>Redis中的HLL是基于string结构实现的，单个HLL的内存<strong>永远小于16kb</strong>，<strong>内存占用低</strong>的令人发指！作为代价，其测量结果是概率性的，<strong>有小于0.81％的误差</strong>。不过对于UV统计来说，这完全可以忽略。</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302127.png" srcset="/img/loading.gif" lazyload alt="1653837988985"></p>
<h3 id="12-2-UV统计-测试百万数据的统计"><a href="#12-2-UV统计-测试百万数据的统计" class="headerlink" title="12.2 UV统计-测试百万数据的统计"></a>12.2 UV统计-测试百万数据的统计</h3><p>测试思路：我们直接利用单元测试，向HyperLogLog中添加100万条数据，看看内存占用和统计效果如何</p>
<p><img src="https://gitee.com/fuyingyou/picgo/raw/master/img_redis/202403191302128.png" srcset="/img/loading.gif" lazyload alt="1653838053608"></p>
<p>经过测试：我们会发生他的误差是在允许范围内，并且内存占用极小</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Redis/" class="category-chain-item">Redis</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Redis/" class="print-no-link">#Redis</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Redis实战</div>
      <div>http://example.com/2023/05/17/Redis/Redis实战/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>fyy-coding</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月17日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/08/19/%E7%AE%97%E6%B3%95/LeetCode/LeetCode%201218.%20%E6%9C%80%E9%95%BF%E5%AE%9A%E5%B7%AE%E5%AD%90%E5%BA%8F%E5%88%97/" title="LeetCode 1218. 最长定差子序列">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">LeetCode 1218. 最长定差子序列</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/10/21/%E7%AE%97%E6%B3%95/LeetCode/LeetCode%201700.%20%E6%97%A0%E6%B3%95%E5%90%83%E5%8D%88%E9%A4%90%E7%9A%84%E5%AD%A6%E7%94%9F%E6%95%B0%E9%87%8F/" title="LeetCode 1700. 无法吃午餐的学生数量">
                        <span class="hidden-mobile">LeetCode 1700. 无法吃午餐的学生数量</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","appKey":"96APiPOtZEiCQlv5h3jjZfbC","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量
        <span id="leancloud-site-pv"></span>
        次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数
        <span id="leancloud-site-uv"></span>
        人
      </span>
    
    

  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/js/leancloud.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
